【问题标题】:Getting "IndexError: Cannot choose from an empty sequence" and do not know why my sequenceis empty获取“IndexError:无法从空序列中选择”并且不知道为什么我的序列为空
【发布时间】:2020-11-09 21:17:20
【问题描述】:

这是完整的代码 该程序应该类似于秘密圣诞老人生成器。人 a 送了 x 件礼物,人 b 送了 y 件礼物,但他们没有得到自己的回报。 问题是我对python只有非常基本的经验,而且发生了这种情况。

import random
number_of_people=int(input("How many participants?"))
list_of_names=[]
list_of_numbers=[]
origional_list_to_use=[]
for i in range (number_of_people):
    name=input("What is the name of person "+str(i+1)+"?")
    number=int(input("How many is "+name+" giving?"))
    list_of_names.append(name)
    list_of_numbers.append(number)
    for i in range (number):
        origional_list_to_use.append(name)
list_to_use=origional_list_to_use
count=0
while count<number_of_people:
    giving=[]
    for i in range (list_of_numbers[count]):
        giving.append(random.choice(list_to_use))
    if list_of_names[count] not in giving:
         print(list_of_names[count]," gives to ",giving)
         count=count+1
         print(list_to_use)
         for giving in list_to_use:
             list_to_use.remove(giving)
    else:
         print("INVALID")
         count=0
         list_to_use=origional_list_to_use

给出一个错误,但为什么我的序列是空的?我在这里做错了什么? 我认为它可能在我的列表中或使用随机?

抱歉,这里是完整的错误位。

Traceback (most recent call last):
  File "C:/Users/Name/Documents/Test.py", line 18, in <module>
    giving.append(random.choice(list_to_use))
  File "C:\Users\Name\AppData\Local\Programs\Python\Python38-32\lib\random.py", line 290, in choice
    raise IndexError('Cannot choose from an empty sequence') from None
IndexError: Cannot choose from an empty sequence

【问题讨论】:

  • 您能否将完整的错误和行号添加到您的问题中?谢谢!
  • 请提供完整的堆栈跟踪。我可以告诉你,这个任务list_to_use=origional_list_to_use 没有做你认为的事情。当你变异 list_to_use 时,你也在变异 original_list_to_use。要复制列表的值,您可以执行list_to_use = [*original_list_to_use] 之类的操作
  • Python 也不会对 for giving in list_to_use: list_to_use.remove(giving) 感到满意,因为您在迭代集合时正在修改它。
  • 你能告诉我你的程序是做什么的吗?
  • @AnnZen 我添加了描述

标签: python list if-statement random


【解决方案1】:

似乎有几个问题。我已经用下面的 cmets 解决了它们:


import random
number_of_people=3
list_of_names=[]
list_of_numbers=[]
origional_list_to_use=[]
for i in range (number_of_people):
    name=input("What is the name of person "+str(i+1)+"?")
    number=int(input("How many is "+name+" giving?"))
    list_of_names.append(name)
    list_of_numbers.append(number)
    for i in range (number):
        origional_list_to_use.append(name)

# prevent mutation of original_list_to_use by
# creating a copy instead of a reference
list_to_use=[*origional_list_to_use]
count=0
while count<number_of_people:
    # you use the name giving later in this block, you can't use that name here
    # giving = []
    giving_list = []
    for i in range (list_of_numbers[count]):
        giving_list.append(random.choice(list_to_use))
    if list_of_names[count] not in giving_list:
         # maybe not what you wanted?
         print(list_of_names[count]," gives to ", giving_list)
         count=count+1
         print(list_to_use)
         for giving in list_to_use:
             list_to_use.remove(giving)
    else:
         print("INVALID")
         count=0
         # do not mutate origional_list_to_use
         list_to_use=[*origional_list_to_use]

【讨论】:

    【解决方案2】:

    请阅读https://stackoverflow.com/help/mcve——它解释了如何在请求帮助时删除无关的细节。 当您让人们更容易帮助您时,答案的质量将会提高。


    你抱怨这失败了:

    list_to_use = []
    random.choice(list_to_use)
    

    当您为该函数提供零个元素可供选择时, 您将看到“无法从空序列中选择”IndexError

    要调试您的程序,您需要关注以下语句:

    list_to_use.remove(giving)
    

    注意这个循环:

    for giving in list_to_use:
        list_to_use.remove(giving)
    

    与分配空列表相同, 就像我上面做的那样。


    或者,考虑保护通话 通过检查确认至少有一个元素可供选择:

    if list_to_use:
        random.choice(list_to_use)
    

    (请注意,如果有单个列表元素 那么它将永远被选中, 它没有随机性, 这可能是你想要的。)

    【讨论】:

      【解决方案3】:

      如果每个参与者可以向同一个人赠送多个礼物,您可以使用

      import random
      
      number_of_people = int(input("How many participants? "))
      names = numbers = gifts = list()
      
      for i in range(number_of_people):
          name = input(f"What is the name of person {i+1}? ")
          number = int(input(f"How many is {name} giving? "))
          names.append(name)
          numbers.append(number)
      
      for name, number in zip(names, numbers):
          choices = [n for n in names if n != name] # Define a list of all the participants this participant can give to
          giving = [random.choice(choices) for _ in range(number)] # Randomly pick a participant from the list *number* times
          print(f'{name} is giving {giving}')
      

      如果每个参与者最多可以向同一个人赠送一份礼物,则可以使用

      import random
      
      number_of_people = int(input("How many participants? "))
      names = numbers = gifts = list()
      
      for i in range(number_of_people):
          name = input(f"What is the name of person {i+1}? ")
          number = int(input(f"How many is {name} giving? "))
          names.append(name)
          numbers.append(number)
      
      for name, number in zip(names, numbers):
          choices = [n for n in names if n != name]
          if number > len(choices): # The participant won't be able to give more than the maximum to be received
              print('INVALID')
              continue
          random.shuffle(choices) # Randomly shuffle the list
          giving = choices[:number] # Take *number* names from the list
          print(f'{name} is giving {giving}')
      

      输入:

      How many participants? 4
      What is the name of person 1? Jannet
      How many is Jannet giving? 3
      What is the name of person 2? Bobby
      How many is Bobby giving? 1
      What is the name of person 3? Symone
      How many is Symone giving? 2
      What is the name of person 4? Timmy
      How many is Timmy giving? 3
      

      输出:

      Jannet is giving ['Symone', 'Bobby', 'Bobby']
      Bobby is giving ['Timmy']
      Symone is giving ['Timmy', 'Bobby']
      Timmy is giving ['Bobby', 'Bobby', 'Jannet']
      

      【讨论】:

        猜你喜欢
        • 2020-09-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-17
        • 1970-01-01
        • 2013-12-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多