如何在python中使用逗号格式化数字

时间:2014-04-13 18:42:24

标签: python formatting

我不得不用python 3.4编写这个滚动程序。我让程序运行正常,但我想在列表而不是行中显示结果,我想在数字的适当位置插入逗号。我是否需要为每个结果输入打印功能,还是有更简单的方法?有没有办法在代码中全局应用格式? 我感谢任何帮助。 谢谢!

这是我的代码:

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)

2 个答案:

答案 0 :(得分:1)

您可以使用dict以更简单的方式存储模具的结果。这将允许您遍历所有结果,而不是为每个结果写一个单独的print语句。它还简化了你的代码!

例如:

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

请注意,对于这个简单示例,我们还可以使用list来存储结果。但是,由于零索引和单索引之间的索引转换,代码将不太清楚。

答案 1 :(得分:0)

这是你的程序简化了一点,用逗号作为千位分隔符:

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

这样,除了分隔符之外,其输出与示例中的输出相同,但IMO删除end=' '只会使其更好。