How to deep copy a list?

前端 未结 8 1364
旧巷少年郎
旧巷少年郎 2020-11-22 03:07

I have some problem with a List copy:

So After I got E0 from \'get_edge\', I make a copy of E0 by calling \'E0_copy =

8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 03:17

    I believe a lot of programmers have run into one or two interview problems where they are asked to deep copy a linked list, however this problem is harder than it sounds!

    in python, there is a module called "copy" with two useful functions

    import copy
    copy.copy()
    copy.deepcopy()
    

    copy() is a shallow copy function, if the given argument is a compound data structure, for instance a list, then python will create another object of the same type (in this case, a new list) but for everything inside old list, only their reference is copied

    # think of it like
    newList = [elem for elem in oldlist]
    

    Intuitively, we could assume that deepcopy() would follow the same paradigm, and the only difference is that for each elem we will recursively call deepcopy, (just like the answer of mbcoder)

    but this is wrong!

    deepcopy() actually preserve the graphical structure of the original compound data:

    a = [1,2]
    b = [a,a] # there's only 1 object a
    c = deepcopy(b)
    
    # check the result
    c[0] is a # return False, a new object a' is created
    c[0] is c[1] # return True, c is [a',a'] not [a',a'']
    

    this is the tricky part, during the process of deepcopy() a hashtable(dictionary in python) is used to map: "old_object ref onto new_object ref", this prevent unnecessary duplicates and thus preserve the structure of the copied compound data

    official doc

提交回复
热议问题