【发布时间】:2020-04-17 18:39:30
【问题描述】:
我通过使用 while 列表创建了一个列表,然后使用了 if 语句。在前两个条件下,代码运行完美,没有任何错误。但在第三种情况下,它显示列表为空。我不知道这里出了什么问题。
代码:
# time table generator with python
import random
no_of_classes = int(input("Please enter the number of classes in a day: "))
name_of_classes = input("Please enter the subject name/name of classes (please separate then by commas): ")
class_name_list = name_of_classes.split(",")
days_in_week = int(input("Enter the number of days in a week for which the school is working:"))
list_1 = [] `list with the problem`
x = 1
while x <= no_of_classes:
list_1.append(x)
x += 1
final_list = []
for j in range(days_in_week):
subject_list = []
if no_of_classes > len(class_name_list):
for i in class_name_list:
a = random.choice(list_1)
subject_list.insert((a - 1), i)
for m in range(no_of_classes - len(class_name_list)):
b = random.choice(class_name_list)
subject_list.append(b)
final_list.append(subject_list)
elif no_of_classes == len(class_name_list):
for i in class_name_list:
a = random.choice(list_1)
subject_list.insert((a-1), i)
final_list.append(subject_list)
else: `having problem with this condition`
temp_class_list = []
list_2 = class_name_list
for m in range(no_of_classes):
n = random.choice(list_2)
a = random.choice(list_1)
list_1.remove(a)
list_2.remove(n)
subject_list.insert((a-1), n)
for k in range(days_in_week):
print(final_list[k])
输出:
Traceback (most recent call last):
File "/Users/arungupta/Documents/trial (delete).py", line 24, in <module>
a = random.choice(list_1)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/random.py", line 301, in choice
raise IndexError('Cannot choose from an empty sequence') from None
IndexError: Cannot choose from an empty sequence
感谢您的帮助。非常感谢!!!
【问题讨论】:
-
no_of_classes的值是多少?如果是0,那么while循环将永远不会触发,因此永远不会填充list_1,您将从空列表中进行选择 -
只有当
no_of_classes的值为0时才会发生这种情况。 -
等等,你正在从
list_1和list_2中删除元素,所以最终你可能会遇到list_1为空的情况,即使它没有以这种方式开始
标签: python python-3.x python-2.7 python-requests