โมดูล array ให้ Typed Arrays แบบ C: เก็บข้อมูล numeric แบบ compact, memory-efficient, เหมาะสำหรับข้อมูลปริมาณมาก
สร้าง Array
>> import array
>>> arr = array.array('i', range(5)) # signed int
>>> arr
array('i', [0, 1, 2, 3, 4])
>>> type(arr)
>>> array.typecodes
'bBuhHiIlLqQfd'
Type Codes
| Code | C Type | Python Type | Bytes |
|---|---|---|---|
b | signed char | int | 1 |
B | unsigned char | int | 1 |
u | Py_UNICODE | Unicode char | 2 |
h | signed short | int | 2 |
H | unsigned short | int | 2 |
i | signed int | int | 2/4 |
I | unsigned int | int | 2/4 |
l | signed long | int | 4/8 |
L | unsigned long | int | 4/8 |
q | signed long long | int | 8 |
Q | unsigned long long | int | 8 |
f | float | float | 4 |
d | double | float | 8 |
จาก Bytes
>> arr1 = array.array('b', b'Hello')
>>> arr1
array('b', [72, 101, 108, 108, 111]) # ASCII codes
Methods หลัก
buffer_info()
>> arr = array.array('i', [0, 1, 2, 3, 4])
>>> arr.buffer_info()
(2201141755144, 5) # (memory address, length)
count(x)
>> arr.count(2)
1
extend(iterable)
>> 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(file, n)
อ่าน n items จาก binary file
>> file = open('test.txt', 'wb')
>>> file.write(b'Hello Python')
>>> file.close()
>>> a = array.array('i')
>>> file = open('test.txt', 'rb')
>>> a.fromfile(file, file.tell()) # file.tell() = bytes count
>>> a
array('i', [1819043144, 2035294319, 1852794996])
append(x) / fromlist(list)
>> a = array.array('i')
>>> a.append(10)
>>> a.fromlist([20, 30, 40, 50])
>>> a
array('i', [10, 20, 30, 40, 50])
insert(i, x)
>> a.insert(2, 25)
>>> a
array('i', [10, 20, 25, 30, 40, 50])
pop([i]) / remove(x)
>> a.pop(2)
25
>>> a.remove(30)
>>> a
array('i', [10, 20, 40, 50])
tofile(file)
>> a = array.array('i', [10, 20, 30, 40, 50])
>>> file = open('test.txt', 'wb')
>>> a.tofile(file)
>>> file.close()
>>> open('test.txt', 'rb').read()
b'\n\x00\x00\x00\x14\x00\x00\x00\x1e\x00\x00\x00(\x00\x00\x002\x00\x00\x00'
Array vs List vs NumPy
| Feature | array.array | list | NumPy |
|---|---|---|---|
| Type enforcement | Strict (single type) | Any | Strict (dtype) |
| Memory | Compact (C-style) | High (object refs) | Compact |
| Math operations | ไม่มี (ต้อง loop) | ไม่มี | Vectorized |
| Dependencies | Built-in | Built-in | External |
| File I/O | tofile/fromfile | pickle/json | npy, csv, etc. |
เมื่อไหร่ใช้ array.array?
- ต้องการ memory efficient storage สำหรับ numeric data
- Binary file I/O (network protocols, hardware interfaces)
- Interoperability กับ C libraries (ctypes, struct)
- ไม่ต้องการ mathematical operations ซับซ้อน (ใช้ NumPy แทน)