RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题 / 1596229
Accepted
Андрей Алексеев
Андрей Алексеев
Asked:2024-10-10 13:23:50 +0000 UTC2024-10-10 13:23:50 +0000 UTC 2024-10-10 13:23:50 +0000 UTC

如何按键数组中指定的顺序对地图进行排序?

  • 772

是的map,或者更确切地说map[string]int

默认情况下,据我了解,Golang它按字母顺序按键对元素进行排序。如何map按给定顺序按键排序?

这段代码:

package main

import (
    "fmt"
)

func main() {
    output := make(map[string]int)

    basket := map[string]int{
        "orange": 5, 
        "apple": 7,
        "mango": 3,
        "strawberry": 9,
    }

    //нужный порядок
    keys := []string{
        "strawberry",
        "mango",
        "orange",
    }

    for _, k := range keys {
        output[k] = basket[k]
    }

    fmt.Printf("вывод output : %+v \n", output)
}

将生成带有按字母顺序排列的键的行:

mango, orange, strawberry
golang
  • 2 2 个回答
  • 35 Views

2 个回答

  • Voted
  1. Pak Uula
    2024-10-10T14:12:44Z2024-10-10T14:12:44Z

    对于打印,map标准库确实按键排序。这就是fmtsort.Sort函数的作用。

    但是Go中键/值的枚举是故意随机的。每次迭代映射中的键时,都可以获得一个新序列:https://go.dev/play/p/wgHyoYTGC-t

    package main
    
    import "fmt"
    
    func main() {
        basket := map[string]int{
            "orange":     5,
            "apple":      7,
            "mango":      3,
            "strawberry": 9,
            "mellon":     1,
            "pineapple":  4,
            "papaya":     1,
        }
    
        for i := 0; i < 5; i++ {
            fmt.Println("Попытка №", i)
            for k := range basket {
                fmt.Printf("  ключ: %+v \n", k)
            }
        }
    }
    
    Попытка № 0
      ключ: apple
      ключ: mango
      ключ: strawberry
      ключ: mellon
      ключ: pineapple
      ключ: papaya
      ключ: orange
    Попытка № 1
      ключ: orange
      ключ: apple
      ключ: mango
      ключ: strawberry
      ключ: mellon
      ключ: pineapple
      ключ: papaya
    Попытка № 2
      ключ: strawberry
      ключ: mellon
      ключ: pineapple
      ключ: papaya
      ключ: orange
      ключ: apple
      ключ: mango
    .
    .
    .
    

    要对地图进行排序,您需要创建一个键值对数组并对其进行排序:https://go.dev/play/p/8SbeIbCTleJ

    package main
    
    import (
        "fmt"
        "slices"
        "strings"
    )
    
    type Pair[K any, V any] struct {
        Key   K
        Value V
    }
    
    type PairList[K any, V any] []Pair[K, V]
    
    type PairComparator[K any, V any] func(Pair[K, V], Pair[K, V]) int
    
    func SortMap[K comparable, V any](m map[K]V, cf PairComparator[K, V]) PairList[K, V] {
        result := make(PairList[K, V], len(m))
        i := 0
        for k, v := range m {
            result[i] = Pair[K, V]{k, v}
            i += 1
        }
        slices.SortFunc(result, func(a Pair[K, V], b Pair[K, V]) int { return cf(a, b) })
        return result
    }
    
    func SortMapKeys[K comparable, V any](m map[K]V, cf PairComparator[K, V]) []K {
        result := make([]K, len(m))
        i := 0
        for k := range m {
            result[i] = k
            i += 1
        }
        slices.SortFunc(result, func(a K, b K) int { return cf(Pair[K, V]{a, m[a]}, Pair[K, V]{b, m[b]}) })
        return result
    }
    
    func main() {
        basket := map[string]int{
            "orange":     5,
            "apple":      7,
            "mango":      3,
            "strawberry": 9,
            "mellon":     1,
            "pineapple":  4,
            "papaya":     1,
        }
    
        sortedBasket := SortMap(basket, basketSorter)
        for _, pair := range sortedBasket {
            fmt.Println("sorted basket: ", pair.Key, pair.Value)
        }
    }
    
    func basketSorter(p1, p2 Pair[string, int]) int {
        if p1.Value < p2.Value {
            return -1
        }
        if p1.Value > p2.Value {
            return 1
        }
        return strings.Compare(p1.Key, p2.Key)
    }
    

    结果:

    sorted basket:  mellon 1
    sorted basket:  papaya 1
    sorted basket:  mango 3
    sorted basket:  pineapple 4
    sorted basket:  orange 5
    sorted basket:  apple 7
    sorted basket:  strawberry 9
    
    • 3
  2. Best Answer
    CrazyElf
    2024-10-10T13:53:18Z2024-10-10T13:53:18Z

    map- 这是键:值形式的未排序集合,不保留插入顺序,使用排序键完成搜索(但这不准确)。常规字典在 Python(直到某个版本,似乎是 3.6)和其他编程语言中的行为方式大致相同。

    要保留插入顺序,您需要编写自己的类,或者使用保留插入顺序的现成包:orderedmap。

    • 1

相关问题

  • windows上的protoc编译错误

  • 递归打印包依赖

  • Golang 算法 XTEA ECB 库“golang.org/x/crypto/xtea”

  • 如何将 IMEI 转换为字节并返回 golang

  • 如何创建文件并将其移动到新目录?

  • go中的函数参数中是否有cv-qualifier的类似物?

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5