【问题标题】:for..in.. print dictionary in random order [duplicate]for..in.. 以随机顺序打印字典 [重复]
【发布时间】:2016-05-24 15:39:59
【问题描述】:

我写了下面的代码,当这段代码执行时,输出是这样的

一个:33.75%

零:32.98%

二:33.27%

我的问题是,为什么它不按顺序排列,我该怎么做?

import random 
a=0
dict = {"zero":0,"one":0,"two":0}
while a < 10000:
    a +=1
    b = random.randrange(0,3)
    if b == 0:
        dict["zero"] += 1
    elif b == 1:
        dict["one"] += 1
    elif b == 2:
        dict["two"] += 1
for item in dict:
    dict[item] /= 100
    dict[item] = str(dict[item])+"%"
    print(item + ":" + dict[item])  

【问题讨论】:

  • 字典没有订单。

标签: python


【解决方案1】:

普通字典没有顺序。相反,请使用 collections 模块中的 OrderedDict

import collections

key_value_pairs = [('zero', 0),
                   ('one', 0),
                   ('two', 0)]

dict = collections.OrderedDict(key_value_pairs)

然后你可以像上面那样做所有事情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-08
    • 1970-01-01
    • 1970-01-01
    • 2017-04-02
    • 1970-01-01
    • 2012-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多