[英]Why does Python list of lists behave differently depending on their declaration?
I am trying to create a list inside another list in Python. 我试图在Python中的另一个列表中创建一个列表。 I noticed that depending on the declaration the final (outer) list behaves differently. 我注意到,根据声明,最终(外部)列表的行为有所不同。
I tried to create list of lists in two different ways. 我尝试以两种不同的方式创建列表列表。 Both cases gave me varies results. 两种情况都给了我不同的结果。
#Case 1
def test():
lt1 = lt2 = list()
for i in range(0, 10):
for j in range(0, 2):
lt1.append(j);
lt2.append(lt1);
lt1 = [];
print (lt2)
if __name__ == "__main__":
test()
#Case 2
def test():
lt1 = list()
lt2 = list()
for i in range(0, 10):
for j in range(0, 2):
lt1.append(j);
lt2.append(lt1);
lt1 = [];
print (lt2)
if __name__ == "__main__":
test()
In case 1 the output is [0, 1, [...], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1]] 在情况1中,输出为[0,1,[...],[0,1],[0,1],[0,1],[0,1],[0,1],[0, 1],[0,1],[0,1],[0,1]]
In case 2 the output is [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1]] which is the expected answer for my implementation. 在情况2中,输出为[[0,1],[0,1],[0,1],[0,1],[0,1],[0,1],[0,1],[ 0,1],[0,1],[0,1]]这是我实现的预期答案。
I wanted to know why the first code snippet acts differently. 我想知道为什么第一个代码段的行为不同。
It's because of the first line: 这是因为第一行:
>>> a = b = []
>>> a
[]
>>> b
[]
>>> a is b
True
>>> a = []
>>> b = []
>>> a is b
False
>>>
With one line as in case 1, it contains the same object, so: 如果情况1中有一行,它包含相同的对象,因此:
>>> a = b = []
>>> a.append(1)
>>> a
[1]
>>> b
[1]
>>>
Which doesn't happen with two lines: 两行不会发生这种情况:
>>> a = []
>>> b = []
>>> a.append(1)
>>> a
[1]
>>> b
[]
>>>
So simply because the first line of case 1 has a
and b
that are the exact same objects, unlike the second case's fist line, that are same values, but different id
( id(a) == id(b)
is the same as a is b
). 因此,仅仅因为案例1的第一行的a
和b
是完全相同的对象,与第二种情况的第一行不同,它们是相同的值,但不同的id
( id(a) == id(b)
与a is b
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.