请看下面的Map
var romanNumeralDict map[int]string = map[int]string{
1000: "M",
900 : "CM",
500 : "D",
400 : "CD",
100 : "C",
90 : "XC",
50 : "L",
40 : "XL",
10 : "X",
9 : "IX",
5 : "V",
4 : "IV",
1 : "I",
}
我期待通过循环这个Map的大小顺序的关键
for k, v := range romanNumeralDict {
fmt.Println("k:", k, "v:", v)
}
但是,这将打印出
k: 1000 v: M
k: 40 v: XL
k: 5 v: V
k: 4 v: IV
k: 900 v: CM
k: 500 v: D
k: 400 v: CD
k: 100 v: C
k: 90 v: XC
k: 50 v: L
k: 10 v: X
k: 9 v: IX
k: 1 v: I
有没有一种方法,我可以把它们按密钥大小的顺序打印出来,我想像这样循环这个Map
k:1
K:4
K:5
K:9
k:10
等等。
5条答案
按热度按时间eoigrqb61#
收集所有键,对它们进行排序,并按键迭代您的map,如下所示:
i2byvkas2#
因为知道
keys
的长度,所以可以通过预分配keys
来使它更快一些:将
Key
和Value
替换为您的键和值类型(包括sort
行)。编辑:Go 1.18终于有了泛型!下面是泛型版本:
Playground example
3okqufwl3#
你可以通过先显式地对键排序,然后按键迭代Map来按顺序迭代Map。因为你从romanNumeralDict开始就知道键的最终大小,所以提前分配一个所需大小的数组会更有效。
uqcuzwp84#
基于@布伦特的回答,我有一次想要在一段非关键代码中排序map键,而不必重复太多。所以这里是为许多不同类型创建通用map迭代函数的起点:
playground
需要强调的是:这段代码效率很低,并且使用了反射,所以它没有编译时类型安全,泛型实现应该有更多的类型保护,处理更多的键类型。但是,对于快速和脏脚本,这可以帮助你入门。你需要根据你希望传递的键类型,在switch块中添加更多的case。
46scxncf5#
您可以使用
MapKeys
获得一个可排序的键数组。在本例中,键的类型为
string
:key.Interface().(string)