通过append在Python中填充列表
我正在练习一些初学者的Python项目,想做一个掷骰子模拟器,它会把所有骰子的总和存储在一个列表里。但是,不知道为什么它没有正常工作。有人能解释一下为什么下面这段代码可以运行:
n=0
a=[]
while n<6:
n+=1
a.append(n)
print(a)
并且能产生[1, 2, 3, 4, 5, 6],而这段代码却不行:
import random
maxnum=6
minnum=1
roll_again="y"
count=0
while roll_again=="y":
tots=[]
print("rolling the dice...")
roll1=(random.randint(minnum,maxnum))
roll2=(random.randint(minnum,maxnum))
count+=1
total=roll1+roll2
print(roll1, roll2)
print("Try #",count, ": Total = ", total,"\n")
roll_again=input("Roll the dice again? Y/N ")
if roll_again!="y" and roll_again!="n":
print("please enter 'y' for yes or 'n' for no")
roll_again=input("Roll the dice again? Y/N ")
tots.append(total)
print(tots)
它只打印出最后的总和,结果是一个只有一个值的列表。我到底漏掉了什么呢?
2 个回答
3
你在每次循环中都把列表 tots=[]
重置了,所以它最多只能存一个元素。试着把这个重置放到循环外面:
tots=[]
while roll_again=="y":
...
tots.append(...)
print(tots)
3
把 tots = []
这行代码移到 while 循环外面,正如 wnnmaw 提出的建议。把它写在循环之前,也就是在 count=0
下面。