【问题标题】:How to get through the whole list with if statement even if the first conditin was met?即使满足第一个条件,如何使用 if 语句遍历整个列表?
【发布时间】:2020-05-02 07:38:15
【问题描述】:

下面的代码是一个刽子手游戏。当if 语句找到第一个字母时,它会停止并且不会进一步遍历列表,因此它不会添加重复项。例如,如果一个单词包含两个a 字母,那么它只会添加第一个。

words = ["harry potter", "i love you forever", "neverland", "pockahontas"]
lives = 3
hangman = list(random.choice(words))
copy_of_hangman = hangman.copy()
print(copy_of_hangman)
for i in range(-6, 6, 2):
    copy_of_hangman[i] = "_"
print(copy_of_hangman)
while lives != 0:
    guess = input("Make your guess: ")
    for letter in hangman:
        if letter == guess:
            copy_of_hangman[hangman.index(letter)] = guess
            print(" ".join(copy_of_hangman))

【问题讨论】:

    标签: python-3.x list for-loop if-statement


    【解决方案1】:

    您需要使用 while 循环。
    所以而不是copy_of_hangman[hangman.index(letter)] = guess 你可以使用类似(未经测试)的东西:

    pos = hangman.index(letter)
    while pos != None:
        copy_of_hangman[pos] = guess
        pos = hangman.index(letter)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-03
      • 1970-01-01
      • 2023-02-01
      • 2011-09-04
      • 2011-02-01
      • 2014-10-11
      • 2018-02-20
      相关资源
      最近更新 更多