当我输入'l'作为输入时,它只会放在一个地方而不是两个地方

问题描述 投票:0回答:2
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中的一个位置,而不是两个位置。

python python-3.x list indexing
2个回答
1
投票
的输入

[list.index(x)方法返回其值等于list.index(x)的第一项的索引。

您需要找到值等于x的项目的所有索引。您可以使用列表理解来做到这一点。

x

然后,将所有索引的值设置为等于indices = [i for i, x in enumerate(choose_list) if x == inp]

inp

0
投票

... 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
© www.soinside.com 2019 - 2024. All rights reserved.