# Python数组接口:array和struct模块
Python提供了几种处理数组和结构化数据的方式,主要包括`array`模块和`struct`模块。下面我将介绍这两个模块的主要功能和用法。
## array模块
`array`模块提供了一种高效存储基本数据类型的序列(如整数、浮点数)。
### 基本用法
```python
import array
# 创建一个整型数组
arr = array.array('i', [1, 2, 3, 4, 5]) # 'i'表示有符号整型
# 添加元素
arr.append(6)
# 访问元素
print(arr[0]) # 输出: 1
# 切片操作
print(arr[1:4]) # 输出: array('i', [2, 3, 4])
# 类型代码
print(arr.typecode) # 输出: 'i'
```
### 类型代码
`array`模块支持以下类型代码:
| 类型代码 | C类型 | Python类型 | 最小字节数 |
|----------|----------------|------------|------------|
| 'b' | signed char | int | 1 |
| 'B' | unsigned char | int | 1 |
| 'u' | Py_UNICODE | Unicode | 2 |
| 'h' | signed short | int | 2 |
| 'H' | unsigned short | int | 2 |
| 'i' | signed int | int | 2 |
| 'I' | unsigned int | int | 2 |
| 'l' | signed long | int | 4 |
| 'L' | unsigned long | int | 4 |
| 'q' | signed long long| int | 8 |
| 'Q' | unsigned long long| int | 8 |
| 'f' | float | float | 4 |
| 'd' | double | float | 8 |
## struct模块
`struct`模块用于在Python值和C结构体之间转换,处理二进制数据。
### 基本用法
```python
import struct
# 打包数据
packed_data = struct.pack('iif', 10, 20, 30.5) # 两个整数和一个浮点数
# 解包数据
unpacked_data = struct.unpack('iif', packed_data)
print(unpacked_data) # 输出: (10, 20, 30.5)
# 计算大小
size = struct.calcsize('iif')
print(size) # 输出: 12 (通常4+4+4字节)
```
### 格式字符
`struct`模块使用格式字符串指定数据的排列方式:
| 字符 | C类型 | Python类型 | 标准大小 |
|------|----------------|------------|----------|
| 'x' | 填充字节 | 无 | 1 |
| 'b' | signed char | int | 1 |
| 'B' | unsigned char | int | 1 |
| 'h' | short | int | 2 |
| 'H' | unsigned short | int | 2 |
| 'i' | int | int | 4 |
| 'I' | unsigned int | int | 4 |
| 'l' | long | int | 4 |
| 'L' | unsigned long | int | 4 |
| 'q' | long long | int | 8 |
| 'Q' | unsigned long long | int | 8 |
| 'f' | float | float | 4 |
| 'd' | double | float | 8 |
| 's' | char[] | bytes | 1 |
| 'p' | char[] | bytes | 1 |
| 'P' | void * | int | |
### 字节顺序/对齐
https://zq.zhaopin.com/moment/73378413
https://zq-mobile.zhaopin.com/moment/73378413
https://zhiq.zhaopin.com/moment/73378413
https://zq.zhaopin.com/moment/73378311
https://zq-mobile.zhaopin.com/moment/73378311
https://zhiq.zhaopin.com/moment/73378311
https://zq.zhaopin.com/moment/73378306
https://zq-mobile.zhaopin.com/moment/73378306
https://zhiq.zhaopin.com/moment/73378306
https://zq.zhaopin.com/moment/73378299
https://zq-mobile.zhaopin.com/moment/73378299
https://zhiq.zhaopin.com/moment/73378299
https://zq.zhaopin.com/moment/73378287
https://zq-mobile.zhaopin.com/moment/73378287
https://zhiq.zhaopin.com/moment/73378287
https://zq.zhaopin.com/moment/73378282
https://zq-mobile.zhaopin.com/moment/73378282
可以在格式字符串前加前缀字符控制字节顺序和对齐:
| 字符 | 字节顺序 | 大小 | 对齐 |
|------|----------|----------|------|
| '@' | 本机 | 本机 | 本机 |
| '=' | 本机 | 标准 | 无 |
| '<' | 小端 | 标准 | 无 |
| '>' | 大端 | 标准 | 无 |
| '!' | 网络 | 标准 | 无 |
## 比较与应用场景
- **array模块**:适合处理单一类型的数值序列,比列表更节省内存
- **struct模块**:适合处理二进制数据,如文件格式、网络协议等
对于更复杂的数值计算,通常推荐使用NumPy库,它提供了更强大高效的数组操作功能。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/34366/viewspace-3101287/ ,如需转载,请注明出处,否则将追究法律责任。