在循环中尝试存储信息

2024-05-28 23:14:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着重新掷多个骰子,每次都要记住上一次的重新掷骰。举个例子,如果我掷5骰子,得到1,2,3,4,5。我问你想重掷哪个骰子-1,3,4然后得到3,2,5,3,5。但正如我在循环中所要求的,它覆盖了以前的新卷,只给出最后一卷。在循环中运行时,如何存储新找到的数字?你知道吗

reroll1 = input("Would you like to reroll? Yes or No: ")
if reroll1 == "Yes" or "yes":
count = 0
times = int(input("How many die would you like to reroll? "))
while count < times:
    whichreroll = input("Reroll die: ")
    if whichreroll == "1":
        reroll1 = random.randint(1,6)
    else:
        reroll1 = die1
    if whichreroll == "2":
        reroll2 = random.randint(1,6)
    else:
        reroll2 = die2
    if whichreroll == "3":
        reroll3 = random.randint(1,6)
    else:
        reroll3 = die3
    if whichreroll == "4":
        reroll4 = random.randint(1,6)
    else:
        reroll4 = die4
    if whichreroll == "5":
        reroll5 = random.randint(1,6)
    else:
        reroll5 = die5
    newset = [reroll1, reroll2, reroll3,reroll4,reroll5]

    count += 1
    print(newset)   

Tags: youinputifcountrandom骰子elselike
2条回答

如果我没弄错你的问题,你可以简单地通过两组列表来实现,一组是你已经拥有的那一组,它是newset,另一组是prevSet。prevSet存储的是结果的最后一个值,因此基本上您可以在每次迭代开始时初始化prevSet,这样就可以

while (count < times):
    prevSet = newset 
    .
    .
    .

你可以通过在骰子滚动块上循环而不是使用所有的if语句来清理很多东西。这是通过使用选定的骰子索引现有的骰子卷列表来完成的。我假设你已经有了一个原始骰子卷的列表,所以我只是做了一个并复制到newset。你知道吗

oldset = [1,2,3,4,5]
reroll1 = str(raw_input("Would you like to reroll? Yes or No: "))
if reroll1.lower() == "yes":
    count = 0
    times = int(input("How many die would you like to reroll? "))
    newset = oldset

    while count < times:
        whichreroll = input("Reroll die: ")
        reroll = random.randint(1,6)
        newset[whichreroll-1]= reroll
        count += 1
        print(newset)  

相关问题 更多 >

    热门问题