【发布时间】:2019-03-04 00:05:18
【问题描述】:
我得到了这个工作,但在制作列表/打电话给他们时很糟糕。任何人都可以将其压缩成列表形式吗? (不是为了家庭作业,已经完成了,只是为了学习机会/练习,所以不要着急。)我假设我的 count 变量可以做成一个列表,并在 for 循环和最终打印期间调用。
这是一个骰子游戏,用于跟踪在掷出 2 个骰子并相加后出现的次数。很容易,我只是在理解列表方面很烂,所以用代码解释会非常有用,我的教科书没有足够地阐述这个话题。第一次在堆栈上发帖,请原谅任何混乱的行话或规则。谢谢!
import random
count2 = 0
count3 = 0
count4 = 0
count5 = 0
count6 = 0
count7 = 0
count8 = 0
count9 = 0
count10 = 0
count11 = 0
count12 = 0
rolls = int(input("How many times would you like to roll? "))
for i in range(rolls):
die1 = random.randint(1, 6)
print("Roll number 1 = " + str(die1))
die2 = random.randint(1, 6)
print("Roll number 2 = " + str(die2))
total = die1 + die2
print(total)
if total == 2:
count2 += 1
elif total == 3:
count3 += 1
elif total == 4:
count4 += 1
elif total == 5:
count5 += 1
elif total == 6:
count6 += 1
elif total == 7:
count7 += 1
elif total == 8:
count8 += 1
elif total == 9:
count9 += 1
elif total == 10:
count10 += 1
elif total == 11:
count11 += 1
elif total == 12:
count12 += 1
print("You rolled " + str(count2) + " 2's")
print("You Rolled " + str(count3) + " 3's")
print("You Rolled " + str(count4) + " 4's")
print("You Rolled " + str(count5) + " 5's")
print("You Rolled " + str(count6) + " 6's")
print("You Rolled " + str(count7) + " 7's")
print("You Rolled " + str(count8) + " 8's")
print("You Rolled " + str(count9) + " 9's")
print("You Rolled " + str(count10) + " 10's")
print("You Rolled " + str(count11) + " 11's")
print("You Rolled " + str(count12) + " 12's")
【问题讨论】: