python中的复制列表
因为我正试图复制一份清单,并用清单的副本做一些事情。不知何故,我的原始列表也被修改了。我已经研究了不同的内存分配和分配列表的不同方式。到目前为止没有运气。。。有什么想法吗python中的复制列表,python,list,memory,multidimensional-array,Python,List,Memory,Multidimensional Array,因为我正试图复制一份清单,并用清单的副本做一些事情。不知何故,我的原始列表也被修改了。我已经研究了不同的内存分配和分配列表的不同方式。到目前为止没有运气。。。有什么想法吗 row = 0 column = 0 table1 = copy.copy(table[:]) temptable = [] temptable = table[:] print id(table) print table print id(table1)
row = 0
column = 0
table1 = copy.copy(table[:])
temptable = []
temptable = table[:]
print id(table)
print table
print id(table1)
print table1
print id(temptable)
print temptable
for i in temptable:
for j in i:
if type(j) == str:
temptable[row][column] = 0
column = column + 1
column = 0
row = row + 1
result=[]
for column in zip(*temptable):
try:
result.append(sum(map(int,column)))
except ValueError:
result.append(0)
print table
print table1
print temptable
/####结果
原始列表包含内部列表:
[[0, 'ZZZ', 'XXX', 'YYY', 'AAA', 0, 0],
['BBB', 1, 1, 0, 26, 28, 0], ...
]
内部列表实际上存储为引用,即:
[ location-of-list-0,
location-of-list-1, ...
]
复制列表时,实际上是将引用列表复制到原始列表中存储的相同列表。这称为浅拷贝,因为它复制引用而不是内容
用于创建完全独立的列表
插图
原始列表
浅拷贝
深度复制
您还需要复制列表中的对象,而不仅仅是引用。您还应该复制内部列表,这样可能会对您有所帮助。由于
[:]
只创建实际应用该切片的列表的副本切片,因此对对象的引用保持不变。
使用deepcopy会递归地复制可以指出的每个项目
class Foo:
def __init__(self):
self.name = "unknown"
def __repr__(self):
return "Foo: " + self.name
def __copy__(self):
f = Foo()
f.name = self.name
return f
def __deepcopy__(self, d):
return self.__copy__()
lst = [Foo()]
lst[0].name = "My first foo"
lst2 = lst[:]
lst2.append(Foo())
lst2[1].name = "My second foo"
print lst
print lst2
输出
[Foo:我的第一个Foo][Foo:我的第一个Foo,Foo:我的第二个Foo] 输出 [Foo:我更改了第一个Foo]
[Foo:我更改了第一个Foo,Foo:我的第二个Foo] 输出 [Foo:我更改了第一个Foo]
[Foo:我又换了第一个Foo!]
列表、元组等确实支持
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu!使用谷歌文档绘制工具,顺便说一句。
class Foo:
def __init__(self):
self.name = "unknown"
def __repr__(self):
return "Foo: " + self.name
def __copy__(self):
f = Foo()
f.name = self.name
return f
def __deepcopy__(self, d):
return self.__copy__()
lst = [Foo()]
lst[0].name = "My first foo"
lst2 = lst[:]
lst2.append(Foo())
lst2[1].name = "My second foo"
print lst
print lst2
lst2[0].name = "I changed the first foo"
print lst
print lst2
from copy import deepcopy
lst[0].name = "My first foo"
lst3 = deepcopy(lst)
lst3[0].name = "I changed the first foo again !"
print lst
print lst3