array --- 數值資料陣列

此模組定義了 array.array 型別:一種節省空間的序列,存放單一固定數值型別的值,可像 list 一樣索引,但其後備為一塊連續記憶體,並可透過緩衝協定存取。

支援的型別碼

單字元的 typecode 引數用以選取元素型別:

型別碼

C 型別

位元組

Python 型別

'b'

signed char

1

int

'B'

unsigned char

1

int

'h'

signed short

2

int

'H'

unsigned short

2

int

'i'

signed int

2 或 4

int

'I'

unsigned int

2 或 4

int

'l'

signed long

4

int

'L'

unsigned long

4

int

'q'

signed long long

8

int

'Q'

unsigned long long

8

int

'f'

float

4

float

'd'

double

8

float

'f''d' 碼需要韌體建置時帶有浮點支援(在多數開發板上為預設)。'i''I' 的確切寬度依主機的 C ABI 而定 --- 在 Cortex-M 移植版上通常為 4 位元組。

類別

class array.array(typecode: str, iterable: Iterable = ())

建立一個元素為指定型別的陣列。陣列的初始內容由 iterable 給定。若未提供,則建立一個空陣列。

除了下列方法之外,陣列物件也實作了緩衝協定。這表示整個陣列的內容可透過 memoryview 或其他使用此協定的介面,以原始位元組的形式存取。

append(val: Any) None

將新元素 val 附加到陣列末端,使其增長。

extend(iterable: Iterable) None

iterable 中所含的新元素附加到陣列末端,使其增長。

__getitem__(index: int | slice) Any

對陣列進行索引讀取,以 a[index] 形式呼叫(其中 aarray)。若 indexint 則傳回一個值,若 index 為切片則傳回一個 array。負索引從末端起算,若索引超出範圍則擲出 IndexError

注意: __getitem__ 無法直接呼叫(a.__getitem__(index) 會失敗),且不存在於 __dict__ 中,但 a[index] 確實可運作。

__setitem__(index: int | slice, value: Any) None

對陣列進行索引寫入,以 a[index] = value 形式呼叫(其中 aarray)。若 indexintvalue 為單一值,若 index 為切片則為一個 array。負索引從末端起算,若索引超出範圍則擲出 IndexError

注意: __setitem__ 無法直接呼叫(a.__setitem__(index, value) 會失敗),且不存在於 __dict__ 中,但 a[index] = value 確實可運作。

__len__() int

傳回陣列中的項目數,以 len(a) 形式呼叫(其中 aarray)。

注意: __len__ 無法直接呼叫(a.__len__() 會失敗),且此方法不存在於 __dict__ 中,但 len(a) 確實可運作。

__add__(other: array) array

傳回一個新的 array,為該陣列與 other 的串接結果,以 a + other 形式呼叫(其中 aother 皆為 arrays)。

注意: __add__ 無法直接呼叫(a.__add__(other) 會失敗),且不存在於 __dict__ 中,但 a + other 確實可運作。

__iadd__(other: array) array

將該陣列與 other 就地串接,以 a += other 形式呼叫(其中 aother 皆為 arrays)。等同於 extend(other)

注意: __iadd__ 無法直接呼叫(a.__iadd__(other) 會失敗),且不存在於 __dict__ 中,但 a += other 確實可運作。

__repr__() str

傳回陣列的字串表示,以 str(a)repr(a) 形式呼叫(其中 aarray)。傳回字串 "array(<type>, [<elements>])",其中 <type> 為該陣列的型別碼字母,而 <elements> 為以逗號分隔的陣列元素清單。

注意: __repr__ 無法直接呼叫(a.__repr__() 會失敗),且不存在於 __dict__ 中,但 str(a)repr(a) 兩者皆可運作。