简体   繁体   English

在Python3中,如何创建数值相等但与其他任何级别的嵌套列表无关的任何级别的嵌套列表

[英]In Python3, how to create a any level nested list which is equal in numeric but independent from other any level nested list

There is a project which I have to implement in python3. 我必须在python3中实现一个项目。 However I get stuck with a problem as below. 但是我遇到了如下问题。

For the single level list like l=[a,b,c] , a,b,c are not iterable, if want to copy it in content, only use n=l[:] , However, when there is multi-level nested, whose a,b,c are iterable, even if 'pointer' a,b,c are new variable, but their reference are still point at the original position. 对于像l=[a,b,c]这样的单层列表,a,b,c是不可迭代的,如果要在内容中复制它,则只能使用n=l[:] ,但是,当存在多层列表时嵌套,其“ a,b,c”是可迭代的,即使“指针” a,b,c是新变量,但它们的引用仍指向原始位置。

a unknown level nested list was transfer as an argument to a function. 未知级别的嵌套列表已作为参数传递给函数。 there will be some operation inside this function to the argument, but I don't want to make any change to the original list object in this function's caller. 该函数内部将对参数进行一些操作,但是我不想对该函数的调用方中的原始列表对象进行任何更改。 So i want to copy this object in to a new object. 所以我想将此对象复制到一个新对象中。

To make it easy to read, I try some method I wish it can work as below: 为了易于阅读,我尝试了一些我希望它可以按以下方式工作的方法:

>>> a=[1,2,3]
>>> b=[a,a,a]
>>> b
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
>>> a[1]=10
>>> b
[[1, 10, 3], [1, 10, 3], [1, 10, 3]]
>>> c=list(b)
>>> c
[[1, 10, 3], [1, 10, 3], [1, 10, 3]]
>>> a[1]=20
>>> c
[[1, 20, 3], [1, 20, 3], [1, 20, 3]]
>>> d=b[:][:]
>>> d
[[1, 20, 3], [1, 20, 3], [1, 20, 3]]
>>> a[1]=30
>>> c
[[1, 30, 3], [1, 30, 3], [1, 30, 3]]
>>> d
[[1, 30, 3], [1, 30, 3], [1, 30, 3]]

But all attempt failed. 但是所有尝试都失败了。

Are there anyone who have a brief and efficient way to create a new equal but independent object? 有谁能以简短有效的方式创建一个新的平等但独立的对象?

I believe the simplest thing would be the following: 我认为最简单的方法如下:

b=[list(a),list(a),list(a)]

The problem in your example is that by doing [a,a,a] you do not create new object. 您的示例中的问题是,通过执行[a,a,a]您不会创建对象。

import copy
my_copy = copy.deepcopy(obj_passed_to_me)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM