有人可以解释原因:
b = 10*[[]]
b[0].append(3)
b现在是:
[[3], [3], [3], [3], [3], [3], [3], [3], [3], [3]]
但如果我这样做:
b = [[] for _ in range(10)]
b[0].append(3)
b现在是:
[[3], [], [], [], [], [], [], [], [], []]
另请注意
10*[[]] == [[] for [] in range(10)]
返回
True
(在Python 3.6.1中测试)
答案 0 :(得分:3)
because:
>>> b = 10*[[]]
>>> b[0] is b[1]
True
>>> b = [[] for _ in range(10)]
>>> b[0] is b[1]
False
>>>