在 python 中有一个方便的字典快捷方式 - setdefault 方法。例如,如果我有表示从字符串到列表的映射的字典,我可以这样写
if key not in map:
map[key] = []
map[key].append(value)
这太冗长了,更像 pythonic 的方式是这样的:
map.setdefault(key, []).append(value)
顺便说一句,有一个 defaultdict 类。
所以我的问题是 - Go 中的 map 是否有类似的东西?我真的很讨厌使用 map[string][]int 和类似的类型。
最佳答案
没有专门针对 map 的东西,但是 nil
是一个有效的空 slice (可以与 append
内置函数一起使用)所以下面的代码:
x := make(map[string][]int)
key := "foo"
x[key] = append(x[key], 1)
无论 key
是否存在于 map 中,都会起作用。
关于go - Python 在 golang 中的 setdefault 模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23188271/