如何用两个索引替换列表中的项目

时间:2018-11-14 07:36:03

标签: 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 == guess]
dashes[x] = guess

我想用dashes中的索引替换为x中的破折号。在"e"为输入的情况下,意味着dashes[3]dashes[4]成为"e"dashes[x] = guess似乎无效。

5 个答案:

答案 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是一个无名函数。