“Deep copy” nested list without using the deepcopy function

强颜欢笑 提交于 2019-11-26 21:42:00

问题


I am trying to copy the nested list a, but do not know how to do it without using the copy.deepcopy function.

a = [[1, 2], [3, 4]]

I used:

b = a[:]

and

b = a[:][:]

But they all turn out to be shallow copy.

Any hints?


回答1:


My entry to simulate copy.deepcopy:

def deepcopy(obj):
    if isinstance(obj, dict):
        return {deepcopy(key): deepcopy(value) for key, value in obj.items()}
    if hasattr(obj, '__iter__'):
        return type(obj)(deepcopy(item) for item in obj)
    return obj

The strategy: iterate across each element of the passed-in object, recursively descending into elements that are also iterable and making new objects of their same type.

I make no claim whatsoever that this is comprehensive or without fault [1] (don't pass in an object that references itself!) but should get you started.

[1] Truly! The point here is to demonstrate, not cover every possible eventuality. The source to copy.deepcopy is 50 lines long and it doesn't handle everything.




回答2:


You can use a LC if there's but a single level.

b = [x[:] for x in a]



回答3:


This is a complete cheat - but will work for lists of "primitives" - lists, dicts, strings, numbers:

def cheat_copy(nested_content):
  return eval(repr(nested_content))

There are probably implications to consider for this - and it will not be particularly fast.




回答4:


I found a way to do it using recursion.

def deep_copy(nested_content):
    if not isinstance(nested_content,list):
        return nested_content
    else:
        holder = []
        for sub_content in nested_content:
            holder.append(deep_copy(sub_content))
        return holder


来源:https://stackoverflow.com/questions/7845152/deep-copy-nested-list-without-using-the-deepcopy-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!