python deepcopy - 在Python中深層複製列表




4 Answers

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]]
list file

我對List副本有一些問題:

所以當我從'get_edge'得到E0之後,我通過調用'E0_copy = list(E0)'複製E0 。 在這裡,我猜E0_copyE0的深層副本,我將E0_copy傳遞給'karger(E)' 。 但在主要功能。
為什麼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

提前致謝!




如果列表的內容是原始數據類型,則可以使用理解

new_list = [i for i in old_list]

您可以將其嵌套為多維列表,例如:

new_grid = [[i for i in row] for row in grid]



關於作為樹的列表,python中的deep_copy可以最緊湊地編寫為

def deep_copy(x):
    if not isinstance(x, list): return x
    else: return map(deep_copy, x)



這更像是pythonic

my_list = [0, 1, 2, 3, 4, 5]  # some list
my_list_copy = list(my_list)  # my_list_copy and my_list does not share reference now.

注意:對於可變類型列表,這是不安全的




Related

python list copy deep-copy