python - 刽子手相同的字符错误
问题描述
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 次或更多次的情况。帮助将不胜感激。
解决方案
你的问题是.index()
只返回第一次出现的字母。正如@schwobaseggl 在评论中所说,您需要获取所有事件的所有索引。
您可以通过使用列表推导来做到这一点:
indices = [i for i in range(len(list_gw)) if list_gw[i] == letter]
推荐阅读
- javascript - jquery拖动删除一个元素会改变其他放置元素的位置
- angular - 如何对角度动态表中的行进行分组?
- google-colaboratory - 在 mnsit 数据集上应用 torchvision.transforms 后,如何使用 cv2_imshow 进行查看?
- python-3.x - 在python中删除复数
- laravel - 离开文本字段后 Laravel livewire 元素给出错误 419
- mongodb - Mongo DB - UpdateMany 列数据
- python - tensorflow 2.x 可以在最新的 Python 上运行吗?
- pine-script - strategy.entry() 没有在应该开仓的时候开仓
- ansible - 使用 Ansible 的日期时差
- ios - 如何防止 Chrome-in-iOS 上的双击放大