如何使用列表1中元素的索引来更改列表2中的索引?

时间:2013-12-18 13:36:14

标签: python list python-2.7 indexing

我将使用哪些代码在 lettersInWord 中查找 guess 的索引值,并将这些内容从' - '更改为猜测 lettersDisplayed

guess = 'o'
lettersInWord = ['n', 'o', 'o', 'n']
lettersDisplayed = ['-', '-', '-', '-']

4 个答案:

答案 0 :(得分:3)

guess = 'o'
word, disp = ['n', 'o', 'o', 'n'], ['-', '-', '-', '-']
print [guess if i == guess else j for i, j in zip(word, disp)]

<强>输出

['-', 'o', 'o', '-']

答案 1 :(得分:2)

指定一个“空白”字符串(在您的情况下为“ - ”),然后使用列表推导来更改项目。

guess = 'o'
blank = '-'
lettersInWord = ['n', 'o', 'o', 'n']

lettersDisplayed = [guess if x == guess else blank for x in lettersInWord]

print lettersDisplayed # ['-', 'o', 'o', '-']
print ''.join(lettersDisplayed) # -oo-

编辑:请注意,这实际上仅适用于一个“猜测”,就像您再次猜测它会忽略您的初始猜测。如果您正在寻找多个猜测,请参阅jonrsharpe的回答。

答案 2 :(得分:1)

我认为您希望在每个disp上保留guess中之前显示的字母。在这种情况下,您可以使用:

blank = '-'
word = list("noon")
disp = [blank for char in word]
for guess in ['m', 'n', 'o']:
    disp = [w if (d == blank and w == guess) else d 
            for w, d in zip(word, disp)]
    print(guess, disp)

这保留了之前的猜测并揭示了新猜测的字母。

答案 3 :(得分:0)

这是一个带有一些循环的简单选项:

guess = 'o'
lettersInWord = ['n', 'o', 'o', 'n']
lettersDisplayed = ['-', '-', '-', '-']

listOfFinds = []
for idx, value in enumerate(lettersInWord):
    if guess == value:
        listOfFinds.append(idx)

for value in listOfFinds:
    lettersDisplayed[value] = guess

print lettersDisplayed

<强>输出:

['-', 'o', 'o', '-']