英文:
Analog of Python's setdefault in golang
问题
在Python中,有一个方便的字典快捷方式——setdefault
方法。例如,如果我有一个表示字符串到列表映射的字典,我可以这样写:
if key not in map:
map[key] = []
map[key].append(value)
这种写法太冗长了,更Pythonic的方式是这样的:
map.setdefault(key, []).append(value)
顺便提一下,还有一个defaultdict
类。
那么我的问题是,在Go语言中是否有类似的东西?我真的很烦恼使用map[string][]int
这样的类型。
英文:
There is handy shortcut for dictionaries in python - setdefault method. For example, if I have dict that represents mapping from string to list, I can write something like this
if key not in map:
map[key] = []
map[key].append(value)
this is too verbose and more pythonic way to do this is like so:
map.setdefault(key, []).append(value)
there is a defaultdict class, by the way.
So my question is - is there something similar for maps in Go? I'm really annoyed working with types like map[string][]int and similar.
答案1
得分: 13
没有专门用于地图的东西,但nil
是一个有效的空切片(可以与append
内置函数一起使用),因此以下代码:
x := make(map[string][]int)
key := "foo"
x[key] = append(x[key], 1)
无论key
是否存在于地图中,都可以正常工作。
英文:
There isn't such a thing specifically for maps, but nil
is a valid empty slice (which can be used with the append
builtin) so the following code:
x := make(map[string][]int)
key := "foo"
x[key] = append(x[key], 1)
Will work regardless of whether key
exists in the map or not.
答案2
得分: 2
使用默认地图,它可以正常工作,play:
m := make(map[string][]int)
m["test0"] = append(m["test0"], 10)
m["test1"] = append(m["test1"], 10)
m["test2"] = append(m["test2"], 10)
英文:
It works fine with the default map, play :
m := make(map[string][]int)
m["test0"] = append(m["test0"], 10)
m["test1"] = append(m["test1"], 10)
m["test2"] = append(m["test2"], 10)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论