首页 > 解决方案 > 刽子手相同的字符错误

问题描述

import timeit

import time

start = timeit.default_timer()

username = input('Enter your username:')

print("Hello,", username, ", do you want to play a game of Hangman?")

question = input("[Y]/[N]?\n")

if question == "Y":
    print("Great, let's start!\n_________")

else:
    print(username, "left the game!")
    time.sleep(2)
    quit()

print('Initializing Game...\nPlease wait...')

time.sleep(5)

game_word = input("Enter the game word:")

list_gw = list(game_word)

word_length = len(list_gw)

print("The word is", word_length, "characters long")

lives = 7
guesses = 0
player_guess = []

while lives > 0:
    letter = input("Enter your guess(lowercase only):\n")
    if letter not in list_gw:
        print("False")
        lives -= 1
        print('You have', lives, 'more lives')
        guesses += 1
    if letter in list_gw:
        print('True')
        print(list_gw.index(letter))
        guesses += 1
        player_guess.insert(list_gw.index(letter), letter)
        if player_guess == list_gw:
            print("You WON!")
            print("It took you only", guesses, "guesses!")
            stop = timeit.default_timer()
            print("This game took", round(stop - start), "seconds")
            quit()

我似乎在介绍“game_word”中出现的相同角色的概念时遇到了问题。我很难找到正确的方法来处理用户输入的“字母”在“game_word”中出现 2 次或更多次的情况。帮助将不胜感激。

标签: python

解决方案


你的问题是.index()只返回第一次出现的字母。正如@schwobaseggl 在评论中所说,您需要获取所有事件的所有索引。

您可以通过使用列表推导来做到这一点:

indices = [i for i in range(len(list_gw)) if list_gw[i] == letter] 

推荐阅读