循环列表以删除项目 - 意外行为
Looping over list to delete items - unexpected behavior
未按预期工作的简化方案。我希望有人能指出原因。
nums = [0, 0, 4, 0]
new_list = nums
for i in range(len(nums)):
if nums[i] !=0:
break
del new_list[0]
new_list
我正在尝试删除前面的零。我希望上面的循环删除列表的第一个元素直到它遇到一个非零数字,然后中断。它只是删除第一个零,即使我的 del new_list[0]
语句在循环中。
预期输出:[4, 0]
实际输出:[0, 4, 0]
nums = [0, 0, 4, 0]
new_list = nums # this refer to nums and when you change new_list, nums changes
# do following to make a copy.
new_list = nums[::]
for i in range(len(nums)):
if nums[i] !=0:
break
del new_list[0]
new_list
输出
[4, 0]
python 中的赋值运算符(如 new_list = nums
中所用)不会创建新对象,而只是将另一个名称分配给现有对象。您对 nums
所做的任何更改也会影响 new_list
。
要创建新对象,您可以改为制作浅拷贝:
new_list = nums.copy()
在 python 中,赋值运算符不会在您的 casenum 中使您成为对象的新实例。我建议你阅读 python 中的深拷贝和浅拷贝。正如this article所说
In Python, Assignment statements do not copy objects, they create bindings between a target and an object. When we use = operator user thinks that this creates a new object; well, it doesn’t. It only creates a new variable that shares the reference of the original object. Sometimes a user wants to work with mutable objects, in order to do that user looks for a way to create “real copies” or “clones” of these objects. Or, sometimes a user wants copies that user can modify without automatically modifying the original at the same time, in order to do that we create copies of objects.
您可以使用复制模块进行深度复制。
import copy
nums = [0, 0, 4, 0]
new_list = copy.deepcopy(nums) # using deepcopy for deepcopy
未按预期工作的简化方案。我希望有人能指出原因。
nums = [0, 0, 4, 0]
new_list = nums
for i in range(len(nums)):
if nums[i] !=0:
break
del new_list[0]
new_list
我正在尝试删除前面的零。我希望上面的循环删除列表的第一个元素直到它遇到一个非零数字,然后中断。它只是删除第一个零,即使我的 del new_list[0]
语句在循环中。
预期输出:[4, 0] 实际输出:[0, 4, 0]
nums = [0, 0, 4, 0]
new_list = nums # this refer to nums and when you change new_list, nums changes
# do following to make a copy.
new_list = nums[::]
for i in range(len(nums)):
if nums[i] !=0:
break
del new_list[0]
new_list
输出
[4, 0]
python 中的赋值运算符(如 new_list = nums
中所用)不会创建新对象,而只是将另一个名称分配给现有对象。您对 nums
所做的任何更改也会影响 new_list
。
要创建新对象,您可以改为制作浅拷贝:
new_list = nums.copy()
在 python 中,赋值运算符不会在您的 casenum 中使您成为对象的新实例。我建议你阅读 python 中的深拷贝和浅拷贝。正如this article所说
In Python, Assignment statements do not copy objects, they create bindings between a target and an object. When we use = operator user thinks that this creates a new object; well, it doesn’t. It only creates a new variable that shares the reference of the original object. Sometimes a user wants to work with mutable objects, in order to do that user looks for a way to create “real copies” or “clones” of these objects. Or, sometimes a user wants copies that user can modify without automatically modifying the original at the same time, in order to do that we create copies of objects.
您可以使用复制模块进行深度复制。
import copy
nums = [0, 0, 4, 0]
new_list = copy.deepcopy(nums) # using deepcopy for deepcopy