Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Array Module ใน Python: Typed Arrays สำหรับ Numeric Data

โมดูล 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

CodeC TypePython TypeBytes
bsigned charint1
Bunsigned charint1
uPy_UNICODEUnicode char2
hsigned shortint2
Hunsigned shortint2
isigned intint2/4
Iunsigned intint2/4
lsigned longint4/8
Lunsigned longint4/8
qsigned long longint8
Qunsigned long longint8
ffloatfloat4
ddoublefloat8

จาก 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

Featurearray.arraylistNumPy
Type enforcementStrict (single type)AnyStrict (dtype)
MemoryCompact (C-style)High (object refs)Compact
Math operationsไม่มี (ต้อง loop)ไม่มีVectorized
DependenciesBuilt-inBuilt-inExternal
File I/Otofile/fromfilepickle/jsonnpy, 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 แทน)