本帖最后由 smarth 于 2020-12-9 21:27 编辑
新注:0、由于我直接将typora中文字直接复制在论坛编辑器中,导致排版极其恶劣,在此道歉。
1、由于我不知道创建列表是出现的错误叫什么,且其和‘复制列表’中浅复制极其类似,故把它称为”浅复制“。(欢迎大佬指出真名)
2、本贴所有内容均为原创
(2020.12.9.21:01)
注:0、限于水平(大一),本帖内容难免存在疏漏、错误,欢迎指正讨论。
1、待可能有的讨论结束或我深入学习后将完善此贴
2、本贴中的代码列举了创建列表的几种方式及其输出结果,情况各异。
python 中复制列表有浅复制(shallow copy)和深复制(deep copy)之说
浅复制只是给列表起个别名,并没有真正创建新列表。(留坑,等我学明白再来填坑)
在创建列表时也有类似的情况(详见下列代码)。
代码0:
[Python] 纯文本查看 复制代码 mat = [None] *3
mat[0] = 5
print(mat)
输出:
[Python] 纯文本查看 复制代码 [5, None, None]
代码1:
[Python] 纯文本查看 复制代码 mat = [[None] for i in range(3)]
print(mat)
mat[0] = 5
print(mat)
输出:
[Python] 纯文本查看 复制代码 [[None], [None], [None]]
[5, [None], [None]]
#原本创建的是二维数组,由于使用mat[0] 赋值使原来索引为 0 的‘列表’[None]变为‘数值’5
代码2:
[Python] 纯文本查看 复制代码 at = [[None] for i in range(3)]
print(mat)
mat[0][0] = 5
print(mat)
#与代码2对照
输出:
[Python] 纯文本查看 复制代码 [[None], [None], [None]]
[[5], [None], [None]]
代码3:
[Python] 纯文本查看 复制代码 mat = [None for i in range(3)]
print(mat)
mat[0] = 5
print(mat)
输出:
[Python] 纯文本查看 复制代码 [None, None, None]
[5, None, None]
代码4:
[Python] 纯文本查看 复制代码 mat = [[None for i in range(3)] ]
print(mat)
mat[0][0] = 5
print(mat)
输出:
[Python] 纯文本查看 复制代码 [[None, None, None]]
[[5, None, None]]
代码5:
[Python] 纯文本查看 复制代码 mat = [[None] * 3] *3
print(mat)
mat [0][0]= 5
print(mat)
输出:
[Python] 纯文本查看 复制代码 [[5, None, None], [5, None, None], [5, None, None]]
#出现浅复制
代码6:
[Python] 纯文本查看 复制代码 mat = [[None] for i in range(2)] *3
mat[0][0] = 5
print(mat)
输出:
[Python] 纯文本查看 复制代码 [[5], [None], [5], [None], [5], [None]]
#出现浅复制
代码7:
[Python] 纯文本查看 复制代码 mat = [[None for i in range(2)] for i in range(3)]
mat[0][0] = 5
print(mat)
输出:
[Python] 纯文本查看 复制代码 [[5, None], [None, None], [None, None]]
代码8:
[Python] 纯文本查看 复制代码 mat = [[None] for i in range(3)] for i in range(2)
输出:
代码9:
[Python] 纯文本查看 复制代码 mat = [[None] * 2 for i in range(3)]
mat[0][0] = 5
print(mat)
输出:
[Python] 纯文本查看 复制代码 [[5, None], [None, None], [None, None]]
代码10:
[Python] 纯文本查看 复制代码 mat = [([None] for i in range(3)) for i in range(2)]
输出:
[Python] 纯文本查看 复制代码 [<generator object <listcomp>.<genexpr> at 0x000001D5EE384270>, <generator object <listcomp>.<genexpr> at 0x000001D5EE3842E0>]
可行的一维列表创建并赋初值方式:
[Python] 纯文本查看 复制代码
mat = [None] *3
mat = [None for i in range(3)]
可行的二维列表创建并赋初值方式:
[Python] 纯文本查看 复制代码 mat = [[None for i in range(2)] for i in range(3)]
mat = [[None] * 2 for i in range(3)]
|