简体   繁体   中英

how to format numbers with commas in python

I had to write this die rolling program with python 3.4. I have the program running fine but I would like to display the results in a list rather than a line and I would like to insert commas in their appropriate places in the numbers. Do I need to type out a print function for each individual result or is there an easier way? Is there a way to globally apply formatting in the code? I appreciate any help I can get on this. Thanks!

here is my code:

import random
random.seed()
I = 0
II = 0
III = 0
IV = 0
V = 0
VI = 0
for count in range(6000000):
    die = random.randint(1, 6)
    if die == 1:
        I = I+1
    elif die == 2:
        II = II+1
    elif die == 3:
        III = III+1
    elif die == 4:
        IV = IV+1
    elif die == 5:
        V = V+1
    else:
        if die == 6:
            VI = VI+1

print('Here are the results:', '1 =', V, '2 =', II, '3 =', III, '4 =', IV, \
      '5 =', V, '6 =', VI)
print('Total Rolls equal:', I+II+III+IV+V+VI)

You can use a dict to store the results of your die rolls in a much simpler fashion. This will allow you to loop over all the results instead of writing a separate print statement for each. It also simplifies your code a lot!

For example:

import random
results = {1:0, 2:0, 3:0, 4:0, 5:0, 6:0}
for count in range(6000000):
    die = random.randint(1, 6)
    results[die] += 1

print('Here are the results:')
# Loop over the *keys* of the dictionary, which are the die numbers
for die in results:
    # The format(..., ',d') function formats a number with thousands separators
    print(die, '=', format(results[die], ',d'))
# Sum up all the die results and print them out
print('Total rolls equal:', sum(results.values()))

Here's some sample output:

Here are the results:
1 = 1,000,344
2 = 1,000,381
3 = 999,903
4 = 999,849
5 = 1,000,494
6 = 999,029
Total rolls equal: 6000000

Note that for this simple example, we could also use a list to store the results. However, because of the index translation between zero-indexing and one-indexing, the code would be less clear.

Here is your program simplified a bit and with commas as thousand separators:

import random
from collections import Counter
counts = Counter()
for count in range(6000000):
    counts[random.randint(1, 6)] += 1
print('Here are the results:', end=' ')
for i, c in sorted(counts.items()):
    print('{} = {:,}'.format(i, c), end=' ')
print('Total rolls equal: {:,}'.format(sum(counts.values())))

This way its output is the same as in your example, except for the separators, but IMO removing end=' ' will only make it nicer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM