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

yipeiwu_com5年前Python基础

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

是不是很惊讶?!

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

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设计】。

相关文章

Python实现批量将word转html并将html内容发布至网站的方法

本文实例讲述了Python实现批量将word转html并将html内容发布至网站的方法。分享给大家供大家参考。具体实现方法如下: #coding=utf-8 __author__ =...

Python2和Python3中urllib库中urlencode的使用注意事项

前言 在Python中,我们通常使用urllib中的urlencode方法将字典编码,用于提交数据给url等操作,但是在Python2和Python3中urllib模块中所提供的urle...

Python对CSV、Excel、txt、dat文件的处理

python读取txt文件:(思路:先打开文件,读取文件,最后用for循环输出内容) 1、读取 1.1基于python csv库 #3.读取csv至字典x,y import csv...

Python中的引用和拷贝实例解析

Python中的引用和拷贝实例解析

这篇文章主要介绍了python中的引用和拷贝实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 一.引用 a = ['a',...

Python+OpenCV人脸检测原理及示例详解

Python+OpenCV人脸检测原理及示例详解

关于opencv OpenCV 是 Intel 开源计算机视觉库 (Computer Version) 。它由一系列 C 函数和少量 C++ 类构成,实现了图像处理和计算机视觉方面的很...