【问题标题】:Organize Counter () display in python?在python中组织Counter()显示?
【发布时间】:2013-12-19 18:55:40
【问题描述】:

我正在尝试创建一个骰子模拟器并使用计数器来计算结果出现的次数。这是我写的:

import random
from collections import Counter 


x = input ("How many sides does you dice have?")
y = input ("How many times do you want to roll the dice?")

result = Counter()

for i in range (y):
    z = random.randint (1, x)
    result [z] += 1

print result

这会产生以下内容,这是正确的。

How many sides does you dice have?4
How many times do you want to roll the dice?10
Counter({1: 3, 2: 3, 4: 3, 3: 1})

但我不喜欢结果的显示方式。有没有办法对计数器结果进行排序和组织,使其显示如下?

1: 3
2: 4
3: 3
4: 1

【问题讨论】:

    标签: python random counter simulator dice


    【解决方案1】:

    循环 Counter.most_common() 方法输出:

    for roll, count in result.most_common():
        print '{}: {}'.format(roll, count)
    

    这将输出从最常见到最少的滚动。

    您还可以遍历排序的键:

    for roll in sorted(result):
         print '{}: {}'.format(roll, result[roll])
    

    这会改为按数字顺序输出滚动。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-02
      • 2019-01-21
      • 1970-01-01
      • 1970-01-01
      • 2013-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多