从一个列表中删除影响它的副本 [python 2.7]
Remove from one list impact it's copy [python 2.7]
我创建了一份清单。
当一个项目从一个副本中删除时 - 它也从原始副本中删除。
a = ['alpha', 'beta', 'gamma', 'delta']
b = a
b.remove('alpha')
print 'A list is', a
print 'B list is', b
我应该如何创建一个独立的列表副本,才不会影响原始列表?
晚加
要理解这个错误的原因——应该参考Shallow Copy和Deep Copy的区别Python documentation - 8.17. copy
The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):
- A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
- A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.
您可以使用内置的 copy 模块。
import copy
a = ['alpha', 'beta', 'gamma', 'delta']
# it will perform the shallow copy
b = copy.copy(a)
b.remove('alpha')
print 'A list is', a
print 'B list is', b
为 Python3.x。虽然 copy 模块在 Python3.x
中可用
a = ['alpha', 'beta', 'gamma', 'delta']
b = a.copy()
b.remove('alpha')
print('A list is', a)
print('B list is', b)
希望对您有所帮助
我创建了一份清单。 当一个项目从一个副本中删除时 - 它也从原始副本中删除。
a = ['alpha', 'beta', 'gamma', 'delta']
b = a
b.remove('alpha')
print 'A list is', a
print 'B list is', b
我应该如何创建一个独立的列表副本,才不会影响原始列表?
晚加
要理解这个错误的原因——应该参考Shallow Copy和Deep Copy的区别Python documentation - 8.17. copy
The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):
- A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
- A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.
您可以使用内置的 copy 模块。
import copy
a = ['alpha', 'beta', 'gamma', 'delta']
# it will perform the shallow copy
b = copy.copy(a)
b.remove('alpha')
print 'A list is', a
print 'B list is', b
为 Python3.x。虽然 copy 模块在 Python3.x
中可用a = ['alpha', 'beta', 'gamma', 'delta']
b = a.copy()
b.remove('alpha')
print('A list is', a)
print('B list is', b)
希望对您有所帮助