[英]What better ways could i have written this python code
Hello everyone I'm new to stack overflow and Python i have only been coding in Python for a little under a month now. 大家好,我是刚开始使用堆栈溢出和Python的人,现在我只用不到一个月的时间在Python中进行编码。 I am all about writing leaner and more effective code i was just wondering how i could possibly make this better. 我都是在编写更精简,更有效的代码,我只是想知道如何使它变得更好。 Any help would be greatly appreciated thank you in advance. 任何帮助将不胜感激,谢谢你提前。
<!-- 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
Using a list would make your code much more concise. 使用列表将使您的代码更加简洁。 For example, 例如,
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
Use a list, for one. 使用一个列表。 I've got no access to an interpreter right now, but something like this will do. 我现在无法访问口译员,但是可以这样做。
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.