簡體   English   中英

通過append在python中填充列表

[英]populating a list in python via append

我正在練習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) 

它只是將最后一個總數打印為帶有一個值的列表。 我在這里想念什么?

按照wnnmaw的建議,將tots = []移出while循環。 將其寫在循環之前,在count=0

您可以在每次迭代中重置列表tots=[] ,這樣它就永遠不會容納多個元素。 嘗試將其放在while循環之外:

tots=[]
while roll_again=="y":
    ...
    tots.append(...)
print(tots)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM