【发布时间】: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