如何按顺序遍历 Golang 的地图?

请看我的地图下面

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",
}

我希望循环通过这个地图的大小顺序的关键

  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

有没有办法,我可以打印出来的顺序,大小的关键,所以,我想循环通过这个地图像这样

k:1
K:4
K:5
K:9
k:10

等等。

100187 次浏览

Collect all keys, sort them and iterate your map by key, like the following:

keys := make([]int, 0)
for k, _ := range romanNumeralDict {
keys = append(keys, k)
}
sort.Ints(keys)
for _, k := range keys {
fmt.Println(k, romanNumeralDict[k])
}

You can make it a little faster by preallocating keys because you know its length:

func sortedKeys(m map[Key]Value) ([]Key) {
keys := make([]Key, len(m))
i := 0
for k := range m {
keys[i] = k
i++
}
sort.Keys(keys)
return keys
}

Replace Key and Value with your key and value types (including the sort line). cough generics cough

Edit: Go 1.18 is finally getting generics! Here's the generic version:

// Ordered is a type constraint that matches any ordered type.
// An ordered type is one that supports the <, <=, >, and >= operators.
//
// Note the generics proposal suggests this type will be available from
// a standard "constraints" package in future.
type Ordered interface {
type int, int8, int16, int32, int64,
uint, uint8, uint16, uint32, uint64, uintptr,
float32, float64,
string
}


func sortedKeys[K Ordered, V any](m map[K]V) ([]K) {
keys := make([]K, len(m))
i := 0
for k := range m {
keys[i] = k
i++
}
sort.Slice(keys, func(i, j int) bool { return keys[i] < keys[j] })
return keys
}

Playground example

If execution speed isn't a big concern, you can get a sorted array of keys using MapKeys.

In this example, the keys are of type string:

keys := reflect.ValueOf(myMap).MapKeys()
keysOrder := func(i, j int) bool { return keys[i].Interface().(string) < keys[j].Interface().(string) }
sort.Slice(keys, keysOrder)


// process map in key-sorted order
for _, key := range keys {
value := myMap[key.Interface().(string)]
fmt.Println(key, value)
}
  • See: Getting a slice of keys from a map
  • Warning: This bypasses some compile-time type-safety (panics if not a map)
  • You'll need to cast each key in order to get its raw value: key.Interface().(string)

You can iterate over the map in order by sorting the keys explicitly first, and then iterate over the map by key. Since you know the final size of keys from the romanNumeralDict outset, it is more efficient to allocate an array of the required size up front.

// Slice for specifying the order of the map.
// It is initially empty but has sufficient capacity
// to hold all the keys of the romanNumeralDict map.
keys := make([]int, 0, len(romanNumeralDict))


// Collect keys of the map
i := 0
for k, _ := range romanNumeralDict {
keys[i] = k
i++
}


// Ints sorts a slice of ints in increasing order
sort.Ints(keys)


// Iterate over the map by key with an order
for _, k := range keys {
fmt.Println(k, romanNumeralDict[k])
}

Based on @Brent's answer, I had an occasion where I wanted sorted map keys in a non-critical piece of code, without having to repeat myself too much. So here is a starting point to make a generic map-iteration function for many different types:

func sortedMapIteration(m interface{}, f interface{}) {
// get value and keys
val := reflect.ValueOf(m)
keys := val.MapKeys()
var sortFunc func(i, j int) bool
kTyp := val.Type().Key()


// determine which sorting function to use for the keys based on their types.
switch {
case kTyp.Kind() == reflect.Int:
sortFunc = func(i, j int) bool { return keys[i].Int() < keys[j].Int() }
case kTyp.Kind() == reflect.String:
sortFunc = func(i, j int) bool { return keys[i].String() < keys[j].String() }
}
sort.Slice(keys, sortFunc)


// get the function and call it for each key.
fVal := reflect.ValueOf(f)
for _, key := range keys {
value := val.MapIndex(key)
fVal.Call([]reflect.Value{key, value})
}
}


// example:
func main() {
sortedMapIteration(map[string]int{
"009": 9,
"003": 3,
"910": 910,
}, func(s string, v int) {
fmt.Println(s, v)
})
}

playground

To stress: this code is inefficient and uses reflection, so it does not have compile-time type safety, and a generic implementation should have more type safeguards and handle more key types. However, for quick and dirty scripts this can help you get started. You will need to add more cases to the switch block, according to which key types you expect to pass.