示例代码:
my_list = [[]] * 4
my_list[2].append(3)
print my_list
预期:[[], [], [3], []]
实际:[[3], [3], [3], [3]]
我的推断是,嵌套列表是彼此的副本。有没有办法实现expected
?
答案 0 :(得分:0)
以其他方式分配3
l = [[]] * 4
l[2] = [3]
print(l)
(xenial)vash@localhost:~/python/stack_overflow$ python3.7 rows.py [[], [], [3], []]