Analog of Python's setdefault in golang

huangapple go评论104阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2014年4月21日 06:23:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/23188271.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定