【发布时间】:2021-08-18 21:22:28
【问题描述】:
我正在尝试用 Python 编写一个 Hangman 游戏,我几乎可以用简单的单词来理解它,但是当有重复时它会混淆返回索引。代码如下:
def hangman_game():
words = ["aback", "abaft", "abandoned", "abashed", "aberrant", "abhorrent", "abiding", "abject", "ablaze", "able",
"abnormal", "aboard", "aboriginal", "abortive", "abounding", "abrasive", "abrupt", "absent", "absorbed",
"absorbing", "abstracted", "absurd", "abundant", "abusive", "acceptable", "accessible", "accidental",
"accurate", "acid", "acidic", "acoustic", "acrid", "actually", "ad hoc", "adamant", "adaptable", "addicted",
"adhesive", "adjoining", "adorable", "adventurous", "afraid", "aggressive", "agonizing", "agreeable", "ahead",
"ajar", "alcoholic", "alert", "alike", "alive", "alleged", "alluring", "aloof", "amazing", "ambiguous",
"ambitious", "amuck", "amused", "amusing", "ancient", "angry", "animated", "annoyed", "annoying", "anxious",
word = random.choice(words)
print(f'Random word = {word} (backtesting)')
letter_set = []
word_set = []
for i in word:
word_set.append(i)
print(f'Letter remaining to be found ={word_set}')
while len(letter_set) < len(word_set):
for i in word:
letter = input("Guess a letter: ")
if letter in word_set:
letter_set.insert(word.index(letter)), letter) # issue here
word_set.remove(letter)
print(f'Word with letters removed: {word}')
print(f"Letter {letter} found at word index: {word.index(letter)}")
print(f'Letters found in word: {letter_set}')
print(f'Word set = {word_set}')
else:
print(f'Letter not found in word: {word}')
print(letter_set)
print("".join(map(str, letter_set)))
当它在 word 中找到重复项时,它会从 word_set 中删除重复的字母,而不是从 word 中删除。因此,当它找到像“字母”这样的单词时,它会始终在索引 [1] 处插入“e”。所以它会像“leettr”一样打印。我发现即使没有重复,有时它也会与索引混淆,通常是在较长的单词上,但无法真正弄清楚原因。
我正在考虑让 letter_set 有 i 个“_”,这取决于默认情况下的单词,而不是使用 word_set 替换它。 关于如何始终将字母返回到正确索引的任何建议?
【问题讨论】:
标签: python list indexing duplicates set