in语句只对python中的列表工作一次

时间:2016-12-16 20:04:37

标签: python python-2.7

我正在制作一个简单的基于文本的刽子手游戏,我想检查一个用户输入的字母是否是包含用户猜测的单词字符的列表的一部分。

以下是代码的一部分:

while True:
print "Guess a letter / The word (%d attempts remaining.)" % attempts
guess = raw_input()
if len(guess) == 1:
    if guess in chars:
        blankslist[chars.index(guess) * 2] = guess
        blanks = "".join(str(x) for x in blankslist)
        print blanks
    else:
        print "Nope!"
        attempts -= 1
        if attempts <= 0:
            print "Game Over! The word was %s" % chosen_word
            break

elif len(guess) == len(chosen_word):
    if guess == chosen_word:
        print "Congrats, you won with %d attempts left!" % attempts
    else:
        print 'Oh no, you lost... The correct word was "%s".' % chosen_word
    break

else:
    print("Input a single letter")

但是,对于包含重复字母的单词,例如&#34; hippopotamus&#34;,它只能检测到一个&#34; p&#34;。我怎样才能检测到它们?

编辑:为问过的人添加了整个循环。

1 个答案:

答案 0 :(得分:1)

.index(guess)仅返回它找到的第一个索引。

您可以使用类似的东西来获取所有索引:

positions = [i for i, char in enumerate(chars) if guess == char]

然后遍历此列表:

for p in positions:
    blankslist[p * 2] = guess