Python数组定义方法

WBOY
Release: 2016-06-10 15:05:11
Original
1771 people have browsed it

本文实例讲述了Python数组定义方法。分享给大家供大家参考,具体如下:

Python中没有数组的数据结构,但列表很像数组,如:

a=[0,1,2]

Copy after login

这时:a[0]=0, a[1]=1, a[[2]=2,但引出一个问题,即如果数组a想定义为0到999怎么办?这时可能通过a = range(0, 1000)实现。或省略为a = range(1000).如果想定义1000长度的a,初始值全为0,则 a = [0 for x in range(0, 1000)]

下面是二维数组的定义:

直接定义:

a=[[1,1],[1,1]]

Copy after login

这里定义了一个2*2的,且初始为0的二维数组。

间接定义:

a=[[0 for x in range(10)] for y in range(10)]

Copy after login

这里定义了10*10初始为0的二维数组。

还有更简单的字义二维数组的方法:

b = [[0]*10]*10

Copy after login

定义10*10初始为0的二维数组。

与a=[[0 for x in range(10)] for y in range(10)]比较:print a==b的结果为True。

但用b的定义方法代替a后,以前的可以正常运行的程序也出错了,经过仔细分析得出区别:

a[0][0]=1时,只有a[0][0]为1,其他全为0。

b[0][0]=1时,a[0][0],a[1][0],只到a[9,0]全部为1。

由此得到大数组中的10个小的一维数据全是一个相同的引用,即指向同一地址。
故 b = [[0]*10]*10并不符合我们常规意义上的二维数组。

同时经过试验:c=[0]*10的定义与c=[0 for x in range(10)]有同样的效果,而没有上面相同引用的问题,估计数组c的定义时是值类型相乘,而前面b的用类型的相乘,因为一维数组是一个引用(借用C#中的值类型和引用类型,不知是否合适)。

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》

希望本文所述对大家Python程序设计有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!