数组 — Python 中高效的数值数组

pythonserver side programmingprogramming更新于 2025/5/12 10:20:17

数组是 C/C++、Java 等语言中非常流行的数据结构。在这些语言中,数组被定义为具有相似数据类型的多个元素的集合。Python 没有任何内置的数组等效项。它的 List 和 Tuple 是元素的集合,但它们可能属于不同的类型。

Python 的数组模块模拟 C 类型数组。该模块定义"array"类。以下构造函数创建一个数组对象:

array(typecode, initializer)

typecode 参数确定数组的类型。初始化程序应为具有匹配类型所有元素的序列。

以下语句创建一个整数数组对象:

>>> import array
>>> arr = array.array('i', range(5))
>>> arr
array('i', [0, 1, 2, 3, 4])
>>> type(arr)
<class 'array.array'>
>>> array.typecodes
'bBuhHiIlLqQfd'

array 模块定义了 typecodes 属性,该属性返回一个字符串。字符串中的每个字符代表一个类型代码,指示 C 类型和等效的 Python 类型:

Type codeC TypePython Type
'b'signed charint
'B'unsigned charint
'u'Py_UNICODEUnicode character
'h'signed shortint
'H'unsigned shortint
'i'signed intint
'I'unsigned intint
'l'signed longint
'L'unsigned longint
'q'signed long longint
'Q'unsigned long longint
'f'floatfloat
'd'doublefloat

初始化参数可以是字节类对象。以下示例从字符串的字节表示构建一个数组。

>>> arr1 = array.array('b', b'Hello')
>>> arr1
array('b', [72, 101, 108, 108, 111])

数组类定义以下方法:

array.buffer_info()

此方法返回一个元组 (address, length),给出当前内存地址和用于保存数组内容的缓冲区元素的长度。

>>> arr = array.array('i', [0, 1, 2, 3, 4])
>>> arr.buffer_info()
(2201141755144, 5)

count()

此方法返回数组中某个元素出现的次数。

>>> arr = array.array('i', [0, 1, 2, 3, 4])
>>> arr.count(2)
1

extend()

此方法将 iterable 中的项目附加到数组或 iterable 的末尾,并且必须具有完全相同的类型代码;如果不是,则会引发 TypeError。

>>> arr = array.array('i', [0, 1, 2, 3, 4])
>>> arr1 = array.array('i',[10,20,30])
>>> arr.extend(arr1)
>>> arr
array('i', [0, 1, 2, 3, 4, 10, 20, 30])

fromfile()

此方法从文件对象读取 n 个项目(作为机器值)并附加到数组中。

在下面的例子中,我们首先以二进制写入模式打开一个文件。

>>> file = open('test.txt','wb')
>>> file.write(b'Hello Python')
12
>>> file.close()

我们现在使用此文件将其数据附加到数组对象。

>>> a = array.array('i')
>>> file = open('test.txt','rb')
>>> a.fromfile(file,file.tell())
>>> a
array('i', [1819043144, 2035294319, 1852794996])

append()

此方法将新项目附加到数组末尾

fromlist()

此方法将列表中的项目附加到数组。这相当于 for x in list: a.append(x)

>>> a = array.array('i')
>>> a.append(10)
>>> a
array('i', [10])
>>> num = [20,30,40,50]
>>> a.fromlist(num)
>>> a
array('i', [10, 20, 30, 40, 50])

insert()

在数组中指定位置之前插入一个新项目

>>> a = array.array('i', [10, 20, 30, 40, 50])
>>> a.insert(2,25)
>>> a
array('i', [10, 20, 25, 30, 40, 50])

pop()

此方法在从数组中删除给定索引处的项目后返回该项目。

>>> a = array.array('i', [10, 20, 30, 40, 50])
>>> x = a.pop(2)
>>> x
30
>>> a
array('i', [10, 20, 40, 50])

remove()

此方法从数组中删除给定项的第一次出现。

>>> a = array.array('i', [10, 20, 30, 40, 50])
>>> a.remove(30)
>>> a
array('i', [10, 20, 40, 50])

tofile()

此方法将所有项目写入已启用写入权限的文件对象。

>>> a = array.array('i', [10, 20, 30, 40, 50])
>>> file = open("test.txt","wb")
>>> a.tofile(file)
>>> file.close()
>>> file = open("test.txt","rb")
>>> file.read()
b'\n\x00\x00\x00\x14\x00\x00\x00\x1e\x00\x00\x00(\x00\x00\x002\x00\x00\x00'

相关文章


有用资源