Hangman Game - 列表中的重复字符问题

时间:2017-07-04 14:42:45

标签: python

我一直在制作一个刽子手游戏并遇到了列表问题。如果用户输入与列表中的任何字符匹配,则找到所述列表中的字母位置,然后将其添加到空白列表中的该位置。但是,包含重复字符的“电视”等单词不起作用。相反,它将打印“tel_vis_on”。对不起,如果这是一个模糊的帖子,我不知道术语。

def guess():
    letter = input ("Please enter a letter:")
    if letter in word:
        print ("Correct!")
        letterPlace = word.index(letter)
        answer[letterPlace] = letter
        print (*answer)
    else:
        print ("Wrong!")

    if answer == word :
        print ("You guessed it! Well Done!")
        #end here
    else:
        guess()

from random import choice
objects = ["computer","television"]
word = choice(objects)
word = (list(word))
wordcount = len(word)
answer = ["_"]*wordcount
print (*answer)
guess()

3 个答案:

答案 0 :(得分:4)

在那部分:

if letter in word:
    print ("Correct!")
    letterPlace = word.index(letter)
    answer[letterPlace] = letter

word.index(letter)将返回该字母第一个出现的索引。

所以你只会用字母替换第一个下划线。那样做:

if letter in word:
    print ("Correct!")
    for letterPlace in (idx for idx,l in enumerate(word) if l==letter):
        answer[letterPlace] = letter

代码循环,如果找到字母,生成器表达式会生成索引,以替换下划线。

答案 1 :(得分:1)

如果你愿意,你可以试试这个。如果你不想要太复杂的东西,那就很容易理解了:

def findOccurences(s, ch):
    return [i for i, letter in enumerate(s) if letter == ch]

def guess():
    letter = input ("Please enter a letter:")
    if letter in word:
        print ("Correct!")
        letterPlace = findOccurences(word,letter)
        for i in letterPlace:
            answer[i] = letter
        print (*answer)
    else:
        print ("Wrong!")

    if answer == word :
        print ("You guessed it! Well Done!")
        #end here
    else:
        guess()

from random import choice
objects = ["computer","television"]
word = choice(objects)
word = (list(word))
wordcount = len(word)
answer = ["_"]*wordcount
print (*answer)
guess()

顺便说一句好游戏。

答案 2 :(得分:0)

这里的问题是您只替换第一次出现的字母。要替换所有出现,请使用re函数,如下所示:

def guess():
    letter = input ("Please enter a letter:")
    if letter in word:
        print ("Correct!")
        letterPlace = [m.start() for m in re.finditer(letter, word)]
        for index in letterPlace:
            answer[index] = letter