import random
word_list = ['kill', 'happy']
choose = random.choice(word_list)
choose_list = list(choose)
players_list = ['_'] * len(choose)
while choose_list != players_list:
# inp is the input of the user
inp = input("Input:\n")
# index_inp is the position of the input
index_inp = choose_list.index(inp)
if inp in choose_list:
players_list[index_inp] = inp
print(players_list)
[当单词是kill
且我输入了'l'
时,它只将字符插入到我的players_list
中的一个位置,而不是两个位置。
[list.index(x)
方法返回其值等于list.index(x)
的第一项的索引。
您需要找到值等于x
的项目的所有索引。您可以使用列表理解来做到这一点。
x
然后,将所有索引的值设置为等于indices = [i for i, x in enumerate(choose_list) if x == inp]
。
inp
...
while choose_list != players_list:
inp = input("Input:\n")
indices = [i for i, x in enumerate(choose_list) if x == inp]
for i in indices:
players_list[i] = inp
已经解释了造成您问题的原因,并提供了我认为可以解决的解决方案。话虽如此,您也可以在接受用户输入后仅用一个长的丑陋列表组件来更新此列表:
Keyur Potdar