2017-07-04 58 views
2

我一直在做一個hang子手遊戲,並遇到列表中的問題。如果用戶輸入與列表中的任何字符相匹配,則在該列表中找到字母的位置,然後將其添加到空白列表中的該位置。但是,包含重複字符的「電視」等字詞不起作用。相反,它將打印「tel_vis_on」。對不起,如果這是一個模糊的帖子,我不知道這個術語。Hang子手遊戲 - 列表中的重複字符問題

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() 
+2

'letterPlace = word.index(letter)'返回word中_first_出現的字母的索引。如果您有重複,則無法使用它。 –

回答

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 

代碼迴路,如果找到這封信,發電機表達式生成的指數,以取代下劃線。

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 
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() 

好的遊戲的方式。