为什么我的Python列表是空的,而我从来没有清空过它?

2024-05-23 17:02:10 发布

您现在位置:Python中文网/ 问答频道 /正文

IndexError: pop from empty list

弹出时,列表临时动物不应为空

number_of_animals=12
animals=["Dog","Cat","Rabbit"]
temp_animals=animals
while (number_of_animals)>0:
    temp_animals=animals
    print(temp_animals(0)
    temp_animals.pop(0)
    number_of_animals-=1

它应该在弹出之前将temp_动物设置为=[“狗”、“猫”、“兔”]。但是动物名单却在清空自己? 所需的输出应该类似于

''' 
Dog
Dog
Dog
Dog
Dog
Dog
Dog
Dog
Dog
Dog
Dog
Dog
'''

Tags: offromnumber列表poptemplistcat
2条回答

在python中,list类似于一个对象。将列表分配给另一个变量就像指向内存中原始列表的指针(用于优化目的)。您必须使用list.copy()来创建列表的真实副本,而不改变原始副本

尝试使用for循环-

number_of_animals=12
animals=["Dog","Cat","Rabbit"]
for _ in range(number_of_animals):
    print(animals[0])

相关问题 更多 >