Python 如何用两个索引替换列表中的项
我是python的初学者,我正在尝试制作一个刽子手游戏,但我似乎无法让它工作。 这是我的密码:Python 如何用两个索引替换列表中的项,python,python-3.x,list,Python,Python 3.x,List,我是python的初学者,我正在尝试制作一个刽子手游戏,但我似乎无法让它工作。 这是我的密码: word = "street" letters = list(word) dashes = ["_","_","_","_","_","_"] guess = input("Guess the letter. ") #assuming that "e" was the input x = [index for index, value in enumerate(letters) if value ==
word = "street"
letters = list(word)
dashes = ["_","_","_","_","_","_"]
guess = input("Guess the letter. ") #assuming that "e" was the input
x = [index for index, value in enumerate(letters) if value == guess]
dashes[x] = guess
我想替换
破折号中索引位于x
中的破折号。如果“e”
作为输入,表示破折号[3]
和破折号[4]
变为“e”
破折号[x]=猜测似乎不起作用。创建一个新的列表破折号并在每次猜测后重新分配名称要比维护一个你改变的破折号列表容易得多
演示:
您已经编写的代码的直接延续是在x
中的索引上循环:
for i in x:
dashes[i] = guess
或者,您可以将列表理解和循环结合起来:
for i in range(len(word)):
if dashes[i] == '_' and word[i] == guess:
dashes[i] = guess
就我个人而言,我经常使用NumPy,觉得它非常适合解决这个问题:
import numpy as np
word = np.array(list("street"))
dashes = np.full_like(word, "_")
guess = input("Guess the letter. ")
dashes[word == guess] = guess
没有Python循环,只是矢量化计算。:) 或列表理解
:
print([v if i not in x else guess for i,v in enumerate(dashes)])
以下是一个完整的解决方案:
word = "street"
guessed = "_" * len(word)
attempts = 0
while '_' in guessed:
guess = input("Guess the letter:: \n> ")
guessed = [x if guess != letter else guess for letter, x in zip(word, guessed)]
print(' '.join(guessed))
attempts += 1
if attempts > 7:
print('Too many wrong guesses.. You lose.')
break
else:
print('CONGRATULATIONS!')
map将函数应用于列表的每个元素。lambda是一个无名函数。您能给出预期的输出吗?欢迎使用StackOverflow!你能详细说明一下你是如何“似乎无法让它发挥作用”的吗。。没有看到这个,你比我快。我会编辑我的。guessed=[“\uu”for uuuuin word]
=>guessed=“\u”*len(word)
@Jean-Françoisfare谢谢!
word = "street"
guessed = "_" * len(word)
attempts = 0
while '_' in guessed:
guess = input("Guess the letter:: \n> ")
guessed = [x if guess != letter else guess for letter, x in zip(word, guessed)]
print(' '.join(guessed))
attempts += 1
if attempts > 7:
print('Too many wrong guesses.. You lose.')
break
else:
print('CONGRATULATIONS!')
word = "street"
dashes = ['_'] * len(word)
guess = raw_input("Guess the letter. ")
dashes = map(lambda x: x if x == guess else '_', word)