如何在Golang中按顺序迭代Map?

mkh04yzy  于 2023-04-03  发布在  Go
关注(0)|答案(5)|浏览(114)

请看下面的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

等等。

eoigrqb6

eoigrqb61#

收集所有键,对它们进行排序,并按键迭代您的map,如下所示:

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

i2byvkas2#

因为知道keys的长度,所以可以通过预分配keys来使它更快一些:

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
}

KeyValue替换为您的键和值类型(包括sort行)。
编辑:Go 1.18终于有了泛型!下面是泛型版本:

// 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

3okqufwl

3okqufwl3#

你可以通过先显式地对键排序,然后按键迭代Map来按顺序迭代Map。因为你从romanNumeralDict开始就知道键的最终大小,所以提前分配一个所需大小的数组会更有效。

// 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])
}
uqcuzwp8

uqcuzwp84#

基于@布伦特的回答,我有一次想要在一段非关键代码中排序map键,而不必重复太多。所以这里是为许多不同类型创建通用map迭代函数的起点:

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
需要强调的是:这段代码效率很低,并且使用了反射,所以它没有编译时类型安全,泛型实现应该有更多的类型保护,处理更多的键类型。但是,对于快速和脏脚本,这可以帮助你入门。你需要根据你希望传递的键类型,在switch块中添加更多的case。

46scxncf

46scxncf5#

您可以使用MapKeys获得一个可排序的键数组。
在本例中,键的类型为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)
}
  • 参见:Getting a slice of keys from a map
  • 警告:这会绕过一些编译时类型安全(如果不是Map,则会出现异常)
  • 您需要强制转换每个键以获得其原始值:key.Interface().(string)

相关问题