猿问

如何根据另一张地图的键值在 Go 中对地图进行排序?

我需要根据另一个地图的键对地图进行排序,因为我当前返回地图的函数未进行排序,因此我需要它根据此名称顺序保持一致,如 所示。我知道一些功能,但是,我在实现它们时遇到了一些麻烦。重申一下,我需要以与变量相同的方式对名称进行排序;没有字母顺序仅基于一个特定的地图排序。如果有人能帮忙,那就太好了。referencereference


为了澄清,我需要根据与 相同的顺序对来自 testMap() 和 testMap2() 的返回值进行排序。该变量显示两个名称之间的连接(命名约定的差异)。referencereference


package main


import (

    "fmt"

)


var reference = map[string]string{"Ali": "Ali_1", "Cat": "Cat1", "Bob": "Bob"}


func main() {

    testMap() 

}


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

}


隔江千里
浏览 80回答 1
1回答

泛舟湖上清波郎朗

初步说明重申一下评论中的重要内容:Go中的地图没有定义的顺序,因此您无法对它们进行排序或保证它们的顺序。从 Go 地图的实际操作:使用范围循环循环访问映射时,不会指定迭代顺序,并且不能保证从一次迭代到下一次迭代相同。如果需要稳定的迭代顺序,则必须维护指定该顺序的单独数据结构。答您可以循环访问 中的键/值,并使用第一个和第二个键从第一个和第二个映射中获取值。referencepackage mainimport (    "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 mainimport (    "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}或者您可以更改为如下所示:referencevar reference = [][]string{{"Ali", "Ali_1"}, {"Cat", "Cat1"}, {"Bob", "Bob"}}(如果涉及两个以上的地图,这将更加灵活,但必须确保子切片中的顺序与地图顺序匹配。尽管随着我们的进步,这种情况越来越多。你可能会考虑一种完全不同的方法,也许使用更复杂的类型,如结构或其他。或者退后一步,首先考虑一下为什么你有这些不匹配的键。
随时随地看视频慕课网APP

相关分类

Java
我要回答