“深复制”不使用 deepcopy 函数的嵌套列表
我正在尝试复制嵌套列表 a
,但不知道如何在不使用 copy.deepcopy
函数的情况下执行此操作。
a = [[1, 2], [3, 4]]
我用了:
b = a[:]
和
b = a[:][:]
但结果都是浅拷贝。
有什么提示吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我的模拟
copy.deepcopy
的条目:策略:迭代传入对象的每个元素,递归地下降到同样可迭代的元素,并创建相同类型的新对象。
我没有声称这是全面的或没有错误的[1](不要传入引用自身的对象!),但应该可以帮助您开始。
[1] 确实如此!这里的重点是演示,而不是涵盖所有可能的可能性。
copy.deepcopy
的源代码有 50 行长,它并不能处理所有内容。My entry to simulate
copy.deepcopy
: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.如果只有一个级别,则可以使用 LC。
You can use a LC if there's but a single level.
这是一个完整的作弊 - 但适用于“基元”列表 - 列表、字典、字符串、数字:
为此需要考虑很强的安全隐患 - 而且它不会特别快。使用json.dumps和loads会更安全。
This is a complete cheat - but will work for lists of "primitives" - lists, dicts, strings, numbers:
There are strong security implications to consider for this - and it will not be particularly fast. Using json.dumps and loads will be more secure.
我找到了一种使用递归来做到这一点的方法。
I found a way to do it using recursion.
对于递归版本,您必须跟踪辅助列表并每次返回。
For the recursive version, you have to keep track of a secondary list and return each time.