该array模块定义了一个非常类似于a的序列数据结构list,除了所有成员必须具有相同的基本类型。支持的类型都是数字或其他固定大小的基本类型,如字节。

有关某些支持的类型,请参阅下表。标准库文档array 包含完整的类型代码列表。

初始化

使用array描述要允许的数据类型的参数以及可能存储在数组中的初始数据序列来实例化。

array_string.py

import arrayimport binasciis = b'This is the array.'a = array.array('b', s)print('As byte string:', s)print('As array :', a)print('As hex :', binascii.hexlify(a))

在此示例中,数组配置为保存字节序列,并使用简单的字节字符串进行初始化。

$ python3 array_string.pyAs byte string: b'This is the array.'As array : array('b', [84, 104, 105, 115, 32, 105, 115, 32, 116, 104, 101, 32, 97, 114, 114, 97, 121, 46])As hex : b'54686973206973207468652061727261792e'

操纵数组

一个array可延伸并以相同的方式作为其他Python序列以其他方式操纵。

array_sequence.py

import arrayimport pprinta = array.array('i', range(3))print('Initial :', a)a.extend(range(3))print('Extended:', a)print('Slice :', a[2:5])print('Iterator:')print(list(enumerate(a)))

支持的操作包括切片,迭代和添加元素到最后。

$ python3 array_sequence.pyInitial : array('i', [0, 1, 2])Extended: array('i', [0, 1, 2, 0, 1, 2])Slice : array('i', [2, 0, 1])Iterator:[(0, 0), (1, 1), (2, 2), (3, 0), (4, 1), (5, 2)]

数组和文件

可以使用为此目的有效编码的内置方法向文件写入和读取数组的内容。

array_file.py

import arrayimport binasciiimport tempfilea = array.array('i', range(5))print('A1:', a)# Write the array of numbers to a temporary fileoutput = tempfile.NamedTemporaryFile()a.tofile(output.file) # must pass an *actual* fileoutput.flush()# Read the raw datawith open(output.name, 'rb') as input: raw_data = input.read() print('Raw Contents:', binascii.hexlify(raw_data)) # Read the data into an array input.seek(0) a2 = array.array('i') a2.fromfile(input, len(a)) print('A2:', a2)

此示例说明直接从二进制文件读取数据“raw”,而不是将其读入新数组并将字节转换为适当的类型。

$ python3 array_file.pyA1: array('i', [0, 1, 2, 3, 4])Raw Contents: b'0000000001000000020000000300000004000000'A2: array('i', [0, 1, 2, 3, 4])

tofile()用于tobytes()格式化数据,并fromfile() 用于frombytes()将其转换回数组实例。

array_tobytes.py

import arrayimport binasciia = array.array('i', range(5))print('A1:', a)as_bytes = a.tobytes()print('Bytes:', binascii.hexlify(as_bytes))a2 = array.array('i')a2.frombytes(as_bytes)print('A2:', a2)

双方tobytes()并frombytes()就字节字符串,而不是Unicode字符串的工作。

$ python3 array_tobytes.pyA1: array('i', [0, 1, 2, 3, 4])Bytes: b'0000000001000000020000000300000004000000'A2: array('i', [0, 1, 2, 3, 4])

替代字节排序

如果数组中的数据不是本机字节顺序,或者数据需要在发送到具有不同字节顺序(或通过网络)的系统之前进行交换,则可以转换整个数组而无需迭代来自Python的元素。

array_byteswap.py

import arrayimport binasciidef to_hex(a): chars_per_item = a.itemsize * 2 # 2 hex digits hex_version = binascii.hexlify(a) num_chunks = len(hex_version) // chars_per_item for i in range(num_chunks): start = i * chars_per_item end = start + chars_per_item yield hex_version[start:end]start = int('0x12345678', 16)end = start + 5a1 = array.array('i', range(start, end))a2 = array.array('i', range(start, end))a2.byteswap()fmt = '{:>12} {:>12} {:>12} {:>12}'print(fmt.format('A1 hex', 'A1', 'A2 hex', 'A2'))print(fmt.format('-' * 12, '-' * 12, '-' * 12, '-' * 12))fmt = '{!r:>12} {:12} {!r:>12} {:12}'for values in zip(to_hex(a1), a1, to_hex(a2), a2): print(fmt.format(*values))

该byteswap()方法从C中切换数组中项目的字节顺序,因此它比在Python中循环数据更有效。

$ python3 array_byteswap.py A1 hex A1 A2 hex A2------------ ------------ ------------ ------------ b'78563412' 305419896 b'12345678' 2018915346 b'79563412' 305419897 b'12345679' 2035692562 b'7a563412' 305419898 b'1234567a' 2052469778 b'7b563412' 305419899 b'1234567b' 2069246994 b'7c563412' 305419900 b'1234567c' 2086024210

查看原文 >>
相关文章