gpt4 book ai didi

go - 按顺序收集值,每个值都包含一个映射

转载 作者:IT老高 更新时间:2023-10-28 12:57:36 24 4
gpt4 key购买 nike

在代码中迭代返回的map时,由topic函数返回,key没有按顺序出现。

如何让键按顺序排列/对 map 进行排序,以便键按顺序排列且值对应?

这里是 the code .

最佳答案

Go blog: Go maps in action有很好的解释。

When iterating over a map with a range loop, the iteration order isnot specified and is not guaranteed to be the same from one iterationto the next. Since Go 1 the runtime randomizes map iteration order, asprogrammers relied on the stable iteration order of the previousimplementation. If you require a stable iteration order you mustmaintain a separate data structure that specifies that order.

这是我修改后的示例代码版本: http://play.golang.org/p/dvqcGPYy3-

package main

import (
"fmt"
"sort"
)

func main() {
// To create a map as input
m := make(map[int]string)
m[1] = "a"
m[2] = "c"
m[0] = "b"

// To store the keys in slice in sorted order
keys := make([]int, len(m))
i := 0
for k := range m {
keys[i] = k
i++
}
sort.Ints(keys)

// To perform the opertion you want
for _, k := range keys {
fmt.Println("Key:", k, "Value:", m[k])
}
}

输出:

Key: 0 Value: b
Key: 1 Value: a
Key: 2 Value: c

关于go - 按顺序收集值,每个值都包含一个映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23330781/

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