Python创建二维数组实例:避开list引用的常见陷阱
本文详解Python中创建二维数组的三种方法,重点剖析使用乘法操作符*创建二维列表时产生的引用共享陷阱。通过对比直接创建、列表生成式及numpy模块创建法,帮助开发者避免修改单个元素导致整列变更的问题,提供安全高效的二维数组构建方案。
0.目录
1.遇到的问题
2.创建二维数组的办法
•3.1 直接创建法
•3.2 列表生成式法
•3.3 使用模块numpy创建
1.遇到的问题
在编写Python代码的过程中,我曾遭遇一个令人头疼的Bug,险些影响作业提交进度。
具体需求是构建一个二维数组,初始代码如下:
m = n = 3
test = [[0] * m] * n
print("test =", test)
运行上述代码,输出结果如下:
test = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
乍看之下,这个二维数组的结构似乎完全正确。
起初我也认为代码无误,怀疑是其他函数调用出了问题。为了验证,我尝试修改其中一个元素的值:
m = n = 3
test = [[0] * m] * n
print("test =", test)
test[0][0] = 233
print("test =", test)
此时的输出结果如下:
test = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] test = [[233, 0, 0], [233, 0, 0], [233, 0, 0]]
这个结果是否让你感到意外?
这个问题困扰了我整整一个中午。查阅官方文档后,我找到了原因,说明如下:
Note also that the copies are shallow; nested structures are not copied. This often haunts new Python programmers; consider:
>>> lists = [[]] * 3 >>> lists [[], [], []] >>> lists[0].append(3) >>> lists [[3], [3], [3]]
What has happened is that [[]] is a one-element list containing an empty list, so all three elements of [[]] * 3 are (pointers to) this single empty list. Modifying any of the elements of lists modifies this single list. You can create a list of different lists this way:
>>> >>> lists = [[] for i in range(3)] >>> lists[0].append(3) >>> lists[1].append(5) >>> lists[2].append(7) >>> lists [[3], [5], [7]]
这表明,在 matrix = [array] * 3 的操作中,Python仅创建了3个指向同一个内部列表 array 的引用。因此,一旦修改了其中任何一个子列表的内容,所有子列表都会随之改变。
2.创建二维数组的办法
2.1 直接创建法
test = [0, 0, 0], [0, 0, 0], [0, 0, 0]]
这种方法简单直接,但代码冗长繁琐,通常不作为首选。
2.2 列表生成式法
test = [[0 for i in range(m)] for j in range(n)]
掌握列表生成式是一项终身受益的技能。若不熟悉,可参考列表生成式 - 廖雪峰的官方网站进行深入学习。
2.3 使用模块numpy创建
import numpy as np test = np.zeros((m, n), dtype=np.int)
关于模块 numpy.zeros 的更多用法,建议查阅 python中numpy.zeros(np.zeros)的使用方法 一文。
以上这篇Python创建二维数组实例(关于list的一个小坑)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持本站。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













