针对n*m的嵌套列表:
- 直接生成:[[0]*m]*n;直接以列表乘倍数的方式会生成的n个内层列表指向的是同一列表,因此赋值时会该表所有的内层列表的值;
- 列表迭代生成:[[0]*m for _ in range(n)];通过列表迭代的方式生成的n个内层列表指向的是不同的地址,故赋值时仅改变对应列表的元素。
print("-------test1: ")
test1 = [[0]*3]*3
print(test1) #[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
test1[0][0] = 1
print(test1) #[[1, 0, 0], [1, 0, 0], [1, 0, 0]]
print(id(test1))
print(id(test1[0]), id(test1[1]), id(test1[2]))
print("-------test2:列表迭代")
test2 = [[0 for _ in range(3)] for _ in range(3)]
print(test2) #[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
test2[0][0] = 1
print(test2) #[[1, 0, 0], [0, 0, 0], [0, 0, 0]]
print(id(test2))
print(id(test2[0]), id(test2[1]), id(test2[2]))
print("-------test3:组合赋值1")
test3 = [[0 for _ in range(3)]]*3
print(test3) #[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
test3[0][0] = 1
print(test3) #[[1, 0, 0], [1, 0, 0], [1, 0, 0]]
print(id(test3))
print(id(test3[0]), id(test3[1]), id(test3[2]))
print("-------test4:组合赋值2")
test4 = [[0]*3 for _ in range(3)]
print(test4) #[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
test4[0][0] = 1
print(test4) #[[1, 0, 0], [0, 0, 0], [0, 0, 0]]
print(id(test4))
print(id(test4[0]), id(test4[1]), id(test4[2]))
输出情况:
-------test1:
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]
139811340142080
139811340150016 139811340150016 139811340150016
-------test2:列表迭代
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
[[1, 0, 0], [0, 0, 0], [0, 0, 0]]
139811340146432
139811340149248 139811340149120 139811340148736
-------test3:组合赋值1
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]
139811340142336
139811340149376 139811340149376 139811340149376
-------test4:组合赋值2
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
[[1, 0, 0], [0, 0, 0], [0, 0, 0]]
139811340147904
139811339738368 139811339740224 139811340146624