为什么Go的地图迭代顺序在打印时有所不同? [英] Why does Go's map iteration order vary when printing?

查看:122
本文介绍了为什么Go的地图迭代顺序在打印时有所不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  package main 

importfmt

func main(){
sample:= map [string]字符串{
key1:value1,
key2:value2,
key3:value3,
}
for i: = 0; i <3; i ++ {
fmt.Println(sample)
}
}

上面的代码只是打印一个map [string]字符串三次。



我希望它有一个固定的输出,但它显示为以下内容:

  map [key3:value3 key2:value2 key1:value1] 
map [key1:value1 key3: value3 key2:value2]
map [key2:value2 key1:value1 key3:value3]

它不同!



而在python中:

 #/ bin / env python 
#encoding = utf8

sample = {
key1:value1,
key2 value2,
key3:value3,
}
对于范围(3)中的i:
打印样本
/ pre>

OutPut:

  {'key3':'value3','key2':'value2','key1':'value1'} 
{'key3':'value3','key2':'value2','key1 ':'value1'}
{'key3':'value3','key2':'value2','key1':'value1'}`


解决方案

你不能依靠你将获得密钥的顺序。语言规范地图是一个无序的元素组,后来的迭代顺序没有指定地图,不能保证从一个迭代到下一个迭代相同。


package main

import "fmt"

func main(){
    sample := map[string]string{
    "key1":"value1",
    "key2":"value2",
    "key3":"value3",
    }
    for i := 0;i<3;i++{
        fmt.Println(sample)
    }
}

The above go code just print a map[string]string three times.

I expect it to a fixed output,but it shows as the following:

map[key3:value3 key2:value2 key1:value1]
map[key1:value1 key3:value3 key2:value2]
map[key2:value2 key1:value1 key3:value3]

It varies!

while in python:

#!/bin/env python
#encoding=utf8

sample = {
    "key1":"value1",
    "key2":"value2",
    "key3":"value3",
}
for i in range(3):
    print sample

OutPut:

{'key3': 'value3', 'key2': 'value2', 'key1': 'value1'}
{'key3': 'value3', 'key2': 'value2', 'key1': 'value1'}
{'key3': 'value3', 'key2': 'value2', 'key1': 'value1'}`

解决方案

You cannot rely on the order in which you will get the keys. The language spec says "A map is an unordered group of elements", and later "The iteration order over maps is not specified and is not guaranteed to be the same from one iteration to the next."

这篇关于为什么Go的地图迭代顺序在打印时有所不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆