我有什么更好的方法可以编写这个python代码

时间:2015-06-27 02:55:21

标签: python

大家好我是堆栈溢出的新手,Python我只用Python编写了一个月不到一个月。我只是想写更精简和更有效的代码我只是想知道我怎么可能做得更好。非常感谢任何帮助,谢谢你。

<!-- language-all: lang-python -->

from __future__ import division
from random import randint

die1 = 0
die2 = 0
die3 = 0
die4 = 0
die5 = 0
die6 = 0

for rolls in range(0, 10000):
    while True:
        rand = randint(1, 6)
        if rand == 1:
            die1 += 1
            break
        elif rand == 2:
            die2 += 1
            break
        elif rand == 3:
            die3 += 1
            break
        elif rand == 4:
            die4 += 1
            break
        elif rand == 5:
            die5 += 1
            break
        elif rand == 6:
            die6 += 1
            break
print 'the result was'
print 'die1 =', die1
print 'die2 =', die2
print 'die3 =', die3
print 'die4 =', die4
print 'die5 =', die5
print 'die6 =', die6

2 个答案:

答案 0 :(得分:6)

使用列表可以使您的代码更简洁。例如,

from random import randint

dice = [0 for i in range(6)]

for rolls in range(0, 10000):
    rand = randint(1, 6)
    dice[rand-1] += 1

print 'the result was'
print dice

答案 1 :(得分:1)

使用列表。我现在无法获得翻译,但是这样的事情就可以了。

dice = [0, 0, 0, 0, 0, 0]

for rolls in range(0, 10000):
    rand = randint(1, 6)
    dice[rand] = dice[rand] + 1

print 'the result was'
for i in range(0, 6):
    print 'die', i, '=', dice[i]