简体   繁体   English

python中[[]] * 2做了什么?

[英]What does [[]]*2 do in python?

A = [[]]*2

A[0].append("a")
A[1].append("b")

B = [[], []]

B[0].append("a")
B[1].append("b")

print "A: "+ str(A)
print "B: "+ str(B)

Yields: 产量:

A: [['a', 'b'], ['a', 'b']]
B: [['a'], ['b']]

One would expect that the A list would be the same as the B list, this is not the case, both append statements were applied to A[0] and A[1]. 可以预期A列表与B列表相同,但事实并非如此,两个追加语句都应用于A [0]和A [1]。

Why? 为什么?

A = [[]]*2 creates a list with 2 identical elements: [[],[]] . A = [[]]*2创建一个包含2个相同元素的列表: [[],[]] The elements are the same exact list. 元素是完全相同的列表。 So 所以

A[0].append("a")
A[1].append("b")

appends both "a" and "b" to the same list. "a""b"都附加到同一列表中。

B = [[], []] creates a list with 2 distinct elements. B = [[], []]创建一个包含2个不同元素的列表。

In [220]: A=[[]]*2

In [221]: A
Out[221]: [[], []]

This shows that the two elements of A are identical: 这表明A的两个元素是相同的:

In [223]: id(A[0])==id(A[1])
Out[223]: True

In [224]: B=[[],[]]

This shows that the two elements of B are different objects. 这表明B的两个元素是不同的对象。

In [225]: id(B[0])==id(B[1])
Out[225]: False

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

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