我对列表副本有一些问题:
因此,在我从'get_edge'
获得E0
之后,我通过调用'E0_copy = list(E0)'
来复制E0
。这里,我猜E0_copy
是E0
的深层副本,我将E0_copy
传递给'karger(E)'
。而是在main函数中。
为什么for循环之前的'print E0[1:10]'
结果和for循环之后的结果不一样?
下面是我的代码:
def get_graph():
f=open('kargerMinCut.txt')
G={}
for line in f:
ints = [int(x) for x in line.split()]
G[ints[0]]=ints[1:len(ints)]
return G
def get_edge(G):
E=[]
for i in range(1,201):
for v in G[i]:
if v>i:
E.append([i,v])
print id(E)
return E
def karger(E):
import random
count=200
while 1:
if count == 2:
break
edge = random.randint(0,len(E)-1)
v0=E[edge][0]
v1=E[edge][1]
E.pop(edge)
if v0 != v1:
count -= 1
i=0
while 1:
if i == len(E):
break
if E[i][0] == v1:
E[i][0] = v0
if E[i][1] == v1:
E[i][1] = v0
if E[i][0] == E[i][1]:
E.pop(i)
i-=1
i+=1
mincut=len(E)
return mincut
if __name__=="__main__":
import copy
G = get_graph()
results=[]
E0 = get_edge(G)
print E0[1:10] ## this result is not equal to print2
for k in range(1,5):
E0_copy=list(E0) ## I guess here E0_coypy is a deep copy of E0
results.append(karger(E0_copy))
#print "the result is %d" %min(results)
print E0[1:10] ## this is print2
发布于 2013-07-26 13:13:22
E0_copy
不是深度拷贝。您不能使用list()
进行深度复制。( list(...)
和testList[:]
都是浅层副本。)
您可以使用copy.deepcopy(...)
进行列表的深度复制。
deepcopy(x, memo=None, _nil=[])
Deep copy operation on arbitrary Python objects.
请参阅以下代码片段-
>>> a = [[1, 2, 3], [4, 5, 6]]
>>> b = list(a)
>>> a
[[1, 2, 3], [4, 5, 6]]
>>> b
[[1, 2, 3], [4, 5, 6]]
>>> a[0][1] = 10
>>> a
[[1, 10, 3], [4, 5, 6]]
>>> b # b changes too -> Not a deepcopy.
[[1, 10, 3], [4, 5, 6]]
现在看一下deepcopy
操作
>>> import copy
>>> b = copy.deepcopy(a)
>>> a
[[1, 10, 3], [4, 5, 6]]
>>> b
[[1, 10, 3], [4, 5, 6]]
>>> a[0][1] = 9
>>> a
[[1, 9, 3], [4, 5, 6]]
>>> b # b doesn't change -> Deep Copy
[[1, 10, 3], [4, 5, 6]]
发布于 2017-04-16 21:49:32
如果列表的内容是原始数据类型,则可以使用
new_list = [i for i in old_list]
您可以为多维列表嵌套它,如下所示:
new_grid = [[i for i in row] for row in grid]
发布于 2013-07-26 14:22:25
如果你的list elements
是immutable objects
,那么你可以使用它,否则你必须使用copy
模块中的deepcopy
。
您也可以使用最短的方式进行深度复制list
,如下所示。
a = [0,1,2,3,4,5,6,7,8,9,10]
b = a[:] #deep copying the list a and assigning it to b
print id(a)
20983280
print id(b)
12967208
a[2] = 20
print a
[0, 1, 20, 3, 4, 5, 6, 7, 8, 9,10]
print b
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10]
https://stackoverflow.com/questions/17873384
复制相似问题