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 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)