• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Python创建二维数组实例(关于list的一个小坑)

python 搞代码 4年前 (2022-01-08) 31次浏览 已收录 0个评论

下面小编就为大家带来一篇Python创建二维数组实例(关于list的一个小坑)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧

0.目录

1.遇到的问题

2.创建二维数组的办法

•3.1 直接创建法

•3.2 列表生成式法

•3.3 使用模块numpy创建

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]] 

是不是很惊讶?!

这个问题真的是折磨我一个中午,去网上一搜,官方文档中给出的说明

来源gao!daima.com搞$代!码网

是这样的:

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的一个小坑)的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Python创建二维数组实例(关于list的一个小坑)

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址