t0 = [[]] * 2
t1 = [[], []]
t0[0].append('hello')
print t0
t1[0].append('hello')
print t1
The result is
结果是
[['hello'], ['hello']]
[['hello'], []]
But I can't tell their difference.
但我无法区分它们。
2 个解决方案
#1
7
[[]] * 2
makes a shallow copy. Equivalent to:
做一个浅的副本。相当于:
x = []
t0 = [x, x]
However
t1 = [[], []]
Uses two separate empty list literals, they are completely different so mutating one obviously doesn't mutate the other
使用两个单独的空列表文字,它们是完全不同的,所以突变一个显然不会改变另一个
#2
10
When you do [[]] * 2
, it gives you a list containing two of the same list, rather than two lists. It is like doing:
当你执行[[]] * 2时,它会给你一个包含两个相同列表的列表,而不是两个列表。这就像做:
a = []
b = [a, a]
The usual way to make a list containing several different empty lists (or other mutable objects) is to do this:
制作包含多个不同空列表(或其他可变对象)的列表的常用方法是执行此操作:
t1 = [[] for _ in range(5)]
#1
7
[[]] * 2
makes a shallow copy. Equivalent to:
做一个浅的副本。相当于:
x = []
t0 = [x, x]
However
t1 = [[], []]
Uses two separate empty list literals, they are completely different so mutating one obviously doesn't mutate the other
使用两个单独的空列表文字,它们是完全不同的,所以突变一个显然不会改变另一个
#2
10
When you do [[]] * 2
, it gives you a list containing two of the same list, rather than two lists. It is like doing:
当你执行[[]] * 2时,它会给你一个包含两个相同列表的列表,而不是两个列表。这就像做:
a = []
b = [a, a]
The usual way to make a list containing several different empty lists (or other mutable objects) is to do this:
制作包含多个不同空列表(或其他可变对象)的列表的常用方法是执行此操作:
t1 = [[] for _ in range(5)]