python列表中的无限赋值? [重复]

时间:2021-03-21 23:24:24

This question already has an answer here:

这个问题在这里已有答案:

I've come cross this question. Code:

我来过这个问题。码:

>>> values = [0, 1, 2]
>>> values[1] = values
>>> values
[0, [...], 2]

The result I expect is:

我期望的结果是:

[0, [0, 1, 2], 2]

Is this an infinite assignment for python list? What is behind the scene?

这是python列表的无限分配吗?幕后的是什么?

Thanks.

4 个解决方案

#1


6  

You have a recursive list there. values[1] is a reference to values. If you want to store the value of values you need to copy it, the easiest way to do so is

你有一个递归列表。值[1]是对值的引用。如果要存储需要复制它的值的值,最简单的方法是

values[1] = values[:]

#2


3  

You put the same list as the second element inside itself. So the second element of the internal list is itself again.

您将与第二个元素相同的列表放在其自身中。所以内部列表的第二个元素本身就是它。

You need to copy initial list to avoid recursion:

您需要复制初始列表以避免递归:

>>> values[1] = values[:]

#3


2  

You need to copy it:

你需要复制它:

values[1] = values[:]

#4


1  

>>> values = [0, 1, 2]
>>> values[1] = values

you are saying that values[1] is values, which is [0, 1, 2], with values instead of 1, and now values is [0, 1, 2], with values instead of 1, [0, 1, 2], with values instead of 1, [0, 1, 2], with values instead of 1,[0, 1, 2], with values instead of 1, [0, 1, 2], with values instead of 1 ... ... ...

你是说值[1]是值,[0,1,2],值是1而不是1,现在值是[0,1,2],值代替1,[0,1, 2],用值而不是1,[0,1,2],用值而不是1,[0,1,2],用值而不是1,[0,1,2],用值代替1 ...... ......

#1


6  

You have a recursive list there. values[1] is a reference to values. If you want to store the value of values you need to copy it, the easiest way to do so is

你有一个递归列表。值[1]是对值的引用。如果要存储需要复制它的值的值,最简单的方法是

values[1] = values[:]

#2


3  

You put the same list as the second element inside itself. So the second element of the internal list is itself again.

您将与第二个元素相同的列表放在其自身中。所以内部列表的第二个元素本身就是它。

You need to copy initial list to avoid recursion:

您需要复制初始列表以避免递归:

>>> values[1] = values[:]

#3


2  

You need to copy it:

你需要复制它:

values[1] = values[:]

#4


1  

>>> values = [0, 1, 2]
>>> values[1] = values

you are saying that values[1] is values, which is [0, 1, 2], with values instead of 1, and now values is [0, 1, 2], with values instead of 1, [0, 1, 2], with values instead of 1, [0, 1, 2], with values instead of 1,[0, 1, 2], with values instead of 1, [0, 1, 2], with values instead of 1 ... ... ...

你是说值[1]是值,[0,1,2],值是1而不是1,现在值是[0,1,2],值代替1,[0,1, 2],用值而不是1,[0,1,2],用值而不是1,[0,1,2],用值而不是1,[0,1,2],用值代替1 ...... ......