【问题标题】:Trying to store info while in a loop尝试在循环中存储信息
【发布时间】:2013-03-29 21:39:26
【问题描述】:

我正在尝试重掷多个骰子,并且每次都要记住上一次重掷。因此,例如,如果我掷出 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)   

【问题讨论】:

  • 这是什么语言? Python?伪代码?请添加标签和/或写出它是哪种语言。
  • 仅供参考:if reroll1 == "Yes" or "yes": 不会像您认为的那样做。你应该改用if reroll1.lower() == "yes":
  • 你的问题不是很清楚。所以如果你输入 4,你想让最后一个 reroll4 挂掉吗?或者如果你输入 4,你想让 reroll1、2、3、5 保持他们之前的滚动?
  • while i &lt; count: 不像 for i in range(count): 那样 Pythonic
  • 我认为 OP 的问题是滚动列表在每次迭代的循环底部都被完全覆盖。按索引存储每个卷应该可以解决它。

标签: python loops store


【解决方案1】:

您可以通过循环掷骰子块而不是使用所有这些 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)  

【讨论】:

    【解决方案2】:

    如果我的问题是正确的,你可以简单地通过两组列表来做到这一点,一组是你已经拥有的,它是newset,另一组是prevSet。 prevSet 存储结果的最后一个值,所以基本上你可以在每次迭代开始时初始化 prevSet,所以它会是

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

    【讨论】:

    • 我基本上做了你建议的同样的事情,除了设置我的原始列表(这是 dieset,未在此处列出),代替 newset,基本上(我认为),在每次迭代后恢复所有内容。之前它只会更改在循环设置方式中输入的最后一个骰子编号,因此它不会存储先前新找到的数字,然后在最后一次运行时,只更改最新的。无论如何,它现在正在工作:) 感谢您的回复!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-09
    • 2015-05-10
    • 2022-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多