donglan8256 2018-07-08 04:56
浏览 24
已采纳

如何反转golang映射中的项目顺序? [重复]

This question already has an answer here:

I'm new to golang and I'd like to invert the order of appearance of pairs in a map like this so that the last pair comes first:

mapA := map[string]int {
    "cat": 5,
    "dog": 2,
    "fish": 3 ,
}


fmt.Println(mapA)


map[cat:5 dog:2 fish:3]

The resulting map should be like:

map[fish:3 dog:2 cat:5]

It can be a new mapB with the same items but iverted order.

How can I achieve this?

</div>
  • 写回答

1条回答 默认 最新

  • doson1998 2018-07-08 04:58
    关注

    The Go Programming Language Specification

    Map types

    A map is an unordered group of elements.

    For statements

    The iteration order over maps is not specified and is not guaranteed to be the same from one iteration to the next.


    You can't. A Go map is not ordered. A Go map is a hash map (hash table).

    To get the map contents in order (or reverse order), read the map contents into a slice and sort it.


    Hash table - Wikipedia

    A hash table uses a hash function to compute an index into an array of buckets or slots, from which the desired value can be found.

    Drawbacks

    The entries stored in a hash table can be enumerated efficiently (at constant cost per entry), but only in some pseudo-random order. Therefore, there is no efficient way to locate an entry whose key is nearest to a given key. Listing all n entries in some specific order generally requires a separate sorting step, whose cost is proportional to log(n) per entry.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面