【发布时间】:2021-10-22 20:05:20
【问题描述】:
我正在尝试使用for 循环将animals 的所有内容清空到pets。可能有一个简洁的代码,但我想了解我在下面的 3 个代码中哪里出错了。
第一个代码
animals = ['cat','dog','donkey','mouse','pig']
pets=[]
print(animals)
print(pets)
for value in animals:
animals.pop()=value
pets=pets.append(value)
print(animals)
print(pets)
第二个代码
animals = ['cat','dog','donkey','mouse','pig']
pets=[]
print(animals)
print(pets)
for value in animals:
value=aniamls.pop()
pets=pets.append(value)
print(animals)
print(pets)
第三码
animals = ['cat','dog','donkey','mouse','pig']
pets=[]
print(animals)
print(pets)
for value in animals:
value=aniamls.pop()
pets.append(value)
print(animals)
print(pets)
为什么第三个代码至少在运行,而不是第一和第二个代码?
为什么第三个代码中animals的内容没有全部附加到pets上?
【问题讨论】:
-
是什么让你认为前两个没有运行?
-
pets = animals.copy()应该够了 -
animals.pop()=value不是语法上有效的代码。=的右边不能有函数调用。对于第三个代码,请参阅 here 了解为什么会跳过元素。 -
欢迎。您是否尝试运行第三个代码 sn-p?有一个错字 - 在定义
animals时尝试访问aniamls应该不起作用。感谢您花时间提供以某种方式运行的代码 - 第三个 sn-p 应该给出 NameError 并退出...
标签: python list loops for-loop