“深拷贝"不使用Deepcopy功能的嵌套列表

问题描述:

我正在尝试复制嵌套列表a,但不知道如何使用copy.deepcopy函数在没有的情况下执行此操作.

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

我用过:

b = a[:]

b = a[:][:]

但事实证明它们都是浅表副本.

But they all turn out to be shallow copy.

有任何提示吗?

我的模拟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.

无论它是全面的还是没有错误的,我都不会宣称[1](不要传递引用自身的对象!),但应该让您入门.

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]确实如此!这里的重点是演示,而不是涵盖所有可能的可能性. copy.deepcopy的源代码长50行,而 it 不能处理所有内容.

[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.