如何做一个复杂的列表的完全非共享副本? (深度复制不够) [英] How to make a completely unshared copy of a complicated list? (Deep copy is not enough)

查看:127
本文介绍了如何做一个复杂的列表的完全非共享副本? (深度复制不够)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看这个Python代码:

Have a look at this Python code:

a = [1, 2, 3]
b = [4, 5, 6]
c = [[a, b], [b, a]] # [[[1, 2, 3], [4, 5, 6]], [[4, 5, 6], [1, 2, 3]]]
c[0][0].append(99)   # [[[1, 2, 3, 99], [4, 5, 6]], [[4, 5, 6], [1, 2, 3, 99]]]

修改 c 的一个元素会随处修改。也就是说,如果 99 附加到 c [0] [0] ,它也会附加到 c [1] [1] 。我猜这是因为Python聪明地将引用 c [0] [0] 同一对象 c [1] [1] 。 (这是他们的 id()是一样的)

Notice how modifying one element of c modifies that everywhere. That is, if 99 is appended to c[0][0], it is also appended to c[1][1]. I am guessing this is because Python is cleverly referring to the same object for c[0][0] and c[1][1]. (That is their id() is the same.)

问题: c ,以便其列表元素可以安全地在本地修改?以上只是一个例子,我的真正的问题有一个更复杂的列表,但有一个类似的问题。

Question: Is there something that can be done to c so that its list elements can be safely locally modified? Above is just an example, my real problem has a list much more complicated, but having a similar problem.

(对不起的形式问题上面Python的gurus请感觉可自由修改问题或标签以更好地表达此查询。)

(Sorry for the poorly formed question above. Python gurus please feel free to modify the question or tags to better express this query.)

推荐答案

将现有的列表列表转换为无列表是共享的,您可以递归地复制列表。

To convert an existing list of lists to one where nothing is shared, you could recursively copy the list.

deepcopy 将不够,因为它将复制结构

deepcopy will not be sufficient, as it will copy the structure as-is, keeping internal references as references, not copies.

def unshared_copy(inList):
    if isinstance(inList, list):
        return list( map(unshared_copy, inList) )
    return inList

alist = unshared_copy(your_function_returning_lists())

请注意,这假设数据作为列表列表返回(任意嵌套)。
如果容器是不同类型(例如numpy数组,dicts或用户类),你可能需要改变这个。

Note that this assumes the data is returned as a list of lists (arbitrarily nested). If the containers are of different types (eg. numpy arrays, dicts, or user classes), you may need to alter this.

这篇关于如何做一个复杂的列表的完全非共享副本? (深度复制不够)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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