1 回答

TA贡献1818条经验 获得超3个赞
初步说明
重申一下评论中的重要内容:Go中的地图没有定义的顺序,因此您无法对它们进行排序或保证它们的顺序。
从 Go 地图的实际操作:
使用范围循环循环访问映射时,不会指定迭代顺序,并且不能保证从一次迭代到下一次迭代相同。如果需要稳定的迭代顺序,则必须维护指定该顺序的单独数据结构。
答
您可以循环访问 中的键/值,并使用第一个和第二个键从第一个和第二个映射中获取值。reference
package main
import (
"fmt"
)
var reference = map[string]string{"Ali": "Ali_1", "Cat": "Cat1", "Bob": "Bob"}
func main() {
m1 := testMap()
m2 := testMap2()
for key1, key2 := range reference {
v1, _ := m1[key1]
v2, _ := m2[key2]
fmt.Printf("%s/%s: (%d, %d)\n", key1, key2, v1, v2)
// not sure what you want with these, so I'm just printing
}
}
func testMap() map[string]int {
return map[string]int{"Ali_1": 2, "Bob": 3, "Cat1": 3} // goal is to sort this in the same order of keys(names) as the reference variable
}
func testMap2() map[string]int {
return map[string]int{"Ali": 2, "Bob": 3, "Cat": 3} // goal is to sort this in the same order of keys(names) as the reference variable
}
请注意,这仍然不能保证顺序,只是“匹配”键的值已配对。
如果你想要订购,你需要一些有订单的东西(例如切片)。例如:
package main
import (
"fmt"
)
var keyOrder = []string{"Ali", "Cat", "Bob"}
var reference = map[string]string{"Ali": "Ali_1", "Cat": "Cat1", "Bob": "Bob"}
func main() {
m1 := testMap()
m2 := testMap2()
for _, key1 := range keyOrder {
key2, _ := reference[key1]
v1, _ := m1[key1]
v2, _ := m2[key2]
fmt.Printf("%s/%s: (%d, %d)\n", key1, key2, v1, v2)
}
}
func testMap() map[string]int {
return map[string]int{"Ali_1": 2, "Bob": 3, "Cat1": 3} // goal is to sort this in the same order of keys(names) as the reference variable
}
func testMap2() map[string]int {
return map[string]int{"Ali": 2, "Bob": 3, "Cat": 3} // goal is to sort this in the same order of keys(names) as the reference variable
}
或者您可以更改为如下所示:reference
var reference = [][]string{{"Ali", "Ali_1"}, {"Cat", "Cat1"}, {"Bob", "Bob"}}
(如果涉及两个以上的地图,这将更加灵活,但必须确保子切片中的顺序与地图顺序匹配。
尽管随着我们的进步,这种情况越来越多。你可能会考虑一种完全不同的方法,也许使用更复杂的类型,如结构或其他。或者退后一步,首先考虑一下为什么你有这些不匹配的键。
添加回答
举报