golang map 打印无序

huangapple go评论82阅读模式
英文:

golang map prints out of order

问题

为什么地图的打印顺序是错乱的,我该如何使其按顺序打印?

package main

import (
	"fmt"
)

type monthsType struct {
	no   int
	text string
}

var months = map[int]string{
	1:"January", 2:"Fabruary", 3:"March", 4:"April", 5:"May", 6:"June",
	7:"July", 8:"August", 9:"September", 10:"October", 11:"Novenber", 12:"December",
}

func main(){
	for no, month := range months {
		fmt.Print(no)
		fmt.Println("-" + month)
	}
}

打印结果为:

10-October
7-July
1-January
9-September
4-April
5-May
2-Fabruary
12-December
11-Novenber
6-June
8-August
3-March
英文:

Why is the map printing out of order, and how do I get it in to order?

package main

import (
	"fmt"
)

type monthsType struct {
	no   int
	text string
}

var months = map[int]string{
	1:"January", 2:"Fabruary", 3:"March", 4:"April", 5:"May", 6:"June",
	7:"July", 8:"August", 9:"September", 10:"October", 11:"Novenber", 12:"December",
}

func main(){
	for no, month := range months {
		fmt.Print(no)
		fmt.Println("-" + month)
	}
}

Prints out:

10-October
7-July
1-January
9-September
4-April
5-May
2-Fabruary
12-December
11-Novenber
6-June
8-August
3-March

答案1

得分: 17

func DemoSortMap() (int, error) {
fmt.Println("使用数组按编号访问项目:")
am := [2]string{"jan", "feb"}
for i, n := range am {
fmt.Printf("%2d: %s\n", i, n)
}
fmt.Println("映射是无序的:")
mm := map[int]string{2: "feb", 1: "jan"}
for i, n := range mm {
fmt.Printf("%2d: %s\n", i, n)
}
fmt.Println("通过排序后的键列表访问项目:")
si := make([]int, 0, len(mm))
for i := range mm {
si = append(si, i)
}
sort.Ints(si)
for _, i := range si {
fmt.Printf("%2d: %s\n", i, mm[i])
}

return 0, nil

}

英文:

Code:

func DemoSortMap() (int, error) {
    fmt.Println("use an array to access items by number:")
    am := [2]string{"jan", "feb"}
    for i, n := range am {
        fmt.Printf("%2d: %s\n", i, n)
    }
    fmt.Println("maps are non-sorted:")
    mm := map[int]string{2: "feb", 1: "jan"}
    for i, n := range mm {
        fmt.Printf("%2d: %s\n", i, n)
    }
    fmt.Println("access items via sorted list of keys::")
    si := make([]int, 0, len(mm))
    for i := range mm {
        si = append(si, i)
    }
    sort.Ints(si)
    for _, i := range si {
        fmt.Printf("%2d: %s\n", i, mm[i])
    }
    
    return 0, nil
}

(most of it stolen from M. Summerfield's book)

output:

use an array to access items by number:
 0: jan
 1: feb
maps are non-sorted:
 2: feb
 1: jan
access items via sorted list of keys::
 1: jan
 2: feb

答案2

得分: 6

地图没有排序,所以您可以使用切片来对地图进行排序。Mark Summerfield的书《Go编程》在第204页解释了这一点,并且强烈推荐阅读。

英文:

Maps are not sorted so you may use a slice to sort your map. Mark Summerfield's book "Programming in Go" explains this on page 204 and is highly recommended.

答案3

得分: 1

这是非常晚的答案,但根据我所读的,地图是无序的设计,并且是随机的,因此不应依赖于顺序。

除了使用sort包与第二个地图一起使用之外,还可以使用fmt.Prinln(theMap),它将按顺序打印地图。

>fmt:按键排序顺序打印地图

这将通常按以下方式打印地图:

map[key:value
key:value
key:value
]

但这可能不是你想要的...

通过使用fmt.Sprint,如果需要,可以操作字符串。

例如:

s := fmt.Sprint(theMap)
s1 := s[4 : len(s)-1] // 移除map[和]
fmt.Println(s1)
英文:

This is very late answer, but from what I have read maps are unsorted by design, and are random as one should not rely on the order.

Besides using the sort package together with a second map, one can also use the fmt.Prinln(theMap), which will print the map sorted.

>fmt: print maps in key-sorted order

This will print the map typically as follows:

map[key:value
key:value
key:value
]

But this might not be what you want...

By using the fmt.Sprint one can then manipulate the string if needed.

i.e.

s := fmt.Sprint(theMap)
s1 := s[4 : len(s)-1] // remove map[ and ]
fmt.Println(s1)

huangapple
  • 本文由 发表于 2012年8月24日 19:07:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/12108215.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定