【问题标题】:When I enter 'l' as input it only takes it at one place instead of both当我输入'l'作为输入时,它只在一个地方而不是两个地方
【发布时间】:2020-03-25 05:17:52
【问题描述】:
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


    【解决方案1】:

    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
    

    【讨论】:

    • 谢谢,您能否详细说明一下您在 while 行之后所做的事情。 (我是初学者,不熟悉枚举函数)@KeyurPotdar
    • 查看list comprehensionenumerate的文档即可。
    【解决方案2】:

    Keyur Potdar 已经解释了导致您的问题的原因,并提供了我认为可行的解决方案。话虽如此,您也可以在获取用户输入后仅使用一个长而丑陋的列表组合来更新此列表:

    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 = input("Input:\n")
        # The following is a single list comp for updating players_list:
        players_list = [
            inp if (
                x == inp and players_list[i] == '_'
            ) else players_list[i] for i,x in enumerate(choose_list)
        ]
    
    

    【讨论】:

      猜你喜欢
      • 2013-12-13
      • 2017-07-16
      • 2021-11-24
      • 2021-11-12
      • 2022-01-16
      • 2018-06-09
      • 2016-10-31
      • 2013-11-05
      • 2016-05-06
      相关资源
      最近更新 更多