我是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 == guess]
dashes[x] = guess
我想用dashes
中的索引替换为x
中的破折号。在"e"
为输入的情况下,意味着dashes[3]
和dashes[4]
成为"e"
。 dashes[x] = guess
似乎无效。
答案 0 :(得分:1)
建立新列表dashes
并在每次猜测后重新分配名称比保留要突变的破折号列表要容易得多。
演示:
>>> word = 'street'
>>> dashes = ['_']*len(word)
>>>
>>> guess = 'e'
>>> dashes = [guess if letter == guess else current
...: for letter, current in zip(word, dashes)]
>>> dashes
>>> ['_', '_', '_', 'e', 'e', '_']
>>>
>>> guess = 't'
>>> dashes = [guess if letter == guess else current
...: for letter, current in zip(word, dashes)]
>>> dashes
>>> ['_', 't', '_', 'e', 'e', 't']
答案 1 :(得分:1)
您已经编写的代码的直接延续是循环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循环,只有矢量化计算。 :)
答案 2 :(得分:1)
或path.resolve()
:
list comprehension
答案 3 :(得分:1)
这是一个完整的解决方案:
context.Background()
答案 4 :(得分:1)
word = "street"
dashes = ['_'] * len(word)
guess = raw_input("Guess the letter. ")
dashes = map(lambda x: x if x == guess else '_', word)
map将函数应用于列表的每个元素。 lambda是一个无名函数。