在python中组织计数器()显示?
我正在尝试创建一个骰子模拟器,并使用计数器计算结果出现的次数。这是我写的:在python中组织计数器()显示?,python,random,counter,simulator,dice,Python,Random,Counter,Simulator,Dice,我正在尝试创建一个骰子模拟器,并使用计数器计算结果出现的次数。这是我写的: 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
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
在
计数器上循环。最常见的()方法输出:
for roll, count in result.most_common():
print '{}: {}'.format(roll, count)
这将输出从最常见到最少的辊
您还可以在已排序的键上循环:
for roll in sorted(result):
print '{}: {}'.format(roll, result[roll])
这将以数字顺序输出转鼓