0.目录
1.遇到的问题
2.创建二维数组的办法
"color: #ff0000">1.遇到的问题
今天写Python代码的时候遇到了一个大坑,差点就耽误我交作业了。。。
问题是这样的,我需要创建一个二维数组,如下:
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操作中,只是创建3个指向array的引用,所以一旦array改变,matrix中3个list也会随之改变。
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的一个小坑)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
python,list,二维数组
P70系列延期,华为新旗舰将在下月发布
3月20日消息,近期博主@数码闲聊站 透露,原定三月份发布的华为新旗舰P70系列延期发布,预计4月份上市。
而博主@定焦数码 爆料,华为的P70系列在定位上已经超过了Mate60,成为了重要的旗舰系列之一。它肩负着重返影像领域顶尖的使命。那么这次P70会带来哪些令人惊艳的创新呢?
根据目前爆料的消息来看,华为P70系列将推出三个版本,其中P70和P70 Pro采用了三角形的摄像头模组设计,而P70 Art则采用了与上一代P60 Art相似的不规则形状设计。这样的外观是否好看见仁见智,但辨识度绝对拉满。
更新日志
- 孙悦.1996-伙伴【正大国际】【WAV+CUE】
- 纪钧瀚《钢琴阅读时光 雨中书店聆听轻音乐》[FLAC/分轨][399.62MB]
- 证声音乐图书馆《走向自然 疗心爵士乐》[320K/MP3][87.4MB]
- 证声音乐图书馆《走向自然 疗心爵士乐》[FLAC/分轨][184.94MB]
- 陈慧娴.2018-Priscilla-Ism演唱会3CD(2024环球红馆40复刻系列)【环球】【WAV+CUE】
- 郑秀文.1999-我应该得到(国)【华纳】【WAV+CUE】
- 陈家慧.2011-钢琴酒吧2CD【龙吟唱片】【WAV+CUE】
- 证声音乐图书馆《雨季 蓝调吉他 Rainy Blues》[320K/MP3][45.01MB]
- 证声音乐图书馆《雨季 蓝调吉他 Rainy Blues》[FLAC/分轨][109.13MB]
- 赞多《序章》[320K/MP3][45.54MB]
- 许巍.2004-每一刻都是崭新的【步升大风】【WAV+CUE】
- 群星.2024-四方馆影视原声带【韶愔音乐】【FLAC分轨】
- 陈雷.1997-安锁咧【金圆唱片】【WAV+CUE】
- 关淑怡.2013-MY.FAVORITE.SK.3CD【环球】【WAV+CUE】
- Sweety.2006-花言乔语【丰华】【WAV+CUE】