gpt4 book ai didi

dictionary - 如何更改 map 的默认值

转载 作者:行者123 更新时间:2023-12-01 22:42:43 24 4
gpt4 key购买 nike

我读到Go将值设置为map中数据类型的“零值”。我想知道是否有一种简单的方法来设置不同的默认值,就像在Python中使用defaultdict一样?

为了澄清这个问题,这是我想要实现的Python代码:

from collections import defaultdict
prices=defaultdict(lambda:5) # default value 5 instead of 0
prices[2]=0
prices[3]=0
print(prices) # {2: 0, 3: 0}
for i,p in enumerate ([0,1,2,3,4,5,6]):
if p>prices[i]:
# if price is greater than existing price, compare to 5 when it doesn't exist
prices[i]=p
print(prices) # {0: 5, 1: 5, 2: 2, 3: 3, 4: 5, 5: 5, 6: 6})

最佳答案

您不能更改零值,但是一种简单的模拟方法是将元素访问包装到一个函数中,该函数可以在找不到键的情况下返回您想要的任何内容:

var m = map[int]string{
1: "one",
2: "two",
}

func get(key int) string {
if v, ok := m[key]; ok {
return v
}
return "<missing>"
}

测试它:
fmt.Println(get(1))
fmt.Println(get(2))
fmt.Println(get(3))

输出(在 Go Playground上尝试):
one
two
<missing>

您当然可以使其成为一种方法,并且用法可能更直观,并且通过将其放入包中而不导出 map ,可以确保没有人“绕过” getter方法:
type mymap struct {
m map[int]string
def string
}

func (m mymap) get(key int) string {
if v, ok := m.m[key]; ok {
return v
}
return m.def
}

然后使用它:
m := mymap{
m: map[int]string{
1: "one",
2: "two",
},
def: "<missing>",
}

fmt.Println(m.get(1))
fmt.Println(m.get(2))
fmt.Println(m.get(3))

输出是相同的。在 Go Playground上尝试这个。

关于dictionary - 如何更改 map 的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62382959/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com