Domanda

I am trying to create a dice simulator and using counter to count how many times a result comes up. This is what i wrote:

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

This produces the following, which is correct.

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})

But I don't like the way the result is displayed. Is there a way to sort and organize the counter result so it displays like below?

1: 3
2: 4
3: 3
4: 1
È stato utile?

Soluzione

Loop over the Counter.most_common() method output:

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

This will output rolls from most common to least.

You could also loop over the sorted keys:

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

This outputs rolls in numerical order instead.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top