“深拷贝"不使用Deepcopy功能的嵌套列表 [英] "Deep copy" nested list without using the deepcopy function

查看:110
本文介绍了“深拷贝"不使用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.

这篇关于“深拷贝"不使用Deepcopy功能的嵌套列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆