
2-6 与数组有关的Python程序
前几节是数组的相关知识,对于想进一步学习信息科学的人很有帮助。其实Python语言对于常用的数组数据处理已经有内建的方法,如建立、插入、删除数据,本节将做说明。
在Python程序语言的数据结构中,列表(list)与我们所提的数组非常类似,不过列表结构允许数组元素含不同数据形态,所以在使用上更具弹性,不过也会造成执行速度较差以及需要较多的系统资源。如果数据量少,其实也可以将列表当作数组使用。
Python内建有array模块,使用这个模块可以建立整数、浮点数的数组,在应用上可以用一个字符的type code指定数组的数据形态。

在使用array模块前,必须先导入此模块:
from array import *
2-6-1 建立数组
可以使用array( )方法。
array(typecode[, initializer])
typecode是指所建立数组的数据形态,第2个参数是所建的数组内容。
程序实例ch2_1.py:建立数组然后打印。

执行结果

2-6-2 存取数组内容
我们可以直接使用索引值存取数组内容。
程序实例ch2_2.py:建立数组然后存取数组内容。

执行结果

2-6-3 将数据插入数组
可以使用insert( )方法,将数据插入数组。
insert(i, x)
在索引i位置插入数据x。
程序实例ch2_3.py:先建立数组,然后在索引2位置插入100。

执行结果

append( )则是可以将数据插入数组末端。
程序实例ch2_4.py:先建立数组,然后在数组末端插入100。

执行结果

2-6-4 删除数组元素
可以使用remove(x)方法删除数组中第一个出现的元素x。
程序实例ch2_5.py:先建立数组,然后删除数组元素25。

执行结果

pop(i)可以回传和删除索引i的元素,若省略i相当于i=-1,此时可以回传和删除最后一个元素。
程序实例ch2_6.py:先建立数组,然后第1次使用pop( ),第2次使用pop(2),回传和删除数组元素。

执行结果

2-6-5 搜寻数组元素
可以使用index(x)方法搜寻指定数组元素x的索引。
程序实例ch2_7.py:先建立数组,然后找出数组元素35的索引值。

执行结果

2-6-6 更新数组内容
这一节主要是更改数组某索引内容。
程序实例ch2_8.py:更改索引2的内容为100。

执行结果

2-6-7 Numpy
Python是一个应用范围很广的程序语言,为了应对高速运算,在人工智能领域常用Numpy模块执行相关的数组(array)运算,有关这方面的应用读者可以参考笔者所著的《Python数据科学零基础一本通》。