Python標準庫 array模組

2021-09-26 12:33:18 字數 3511 閱讀 1154

該模組定義了乙個物件型別,可以表示乙個基本值的陣列:整數、浮點數、字元。通過使用型別**在物件建立時指定型別,型別**定義如下表。

type code

c type

python type

minimum size in bytes

notes

'b'signed char

int1

'b'unsigned char

int1

'u'py_unicode

unicode character

2(1)

'h'signed short

int2

'h'unsigned short

int2

'i'signed int

int2

'i'unsigned int

int2

'l'signed long

int4

'l'unsigned long

int4

'q'signed long long

int8

(2)'q'unsigned long long

int8

(2)'f'float

float

4'd'double

float

8陣列物件的資料屬性

陣列物件的方法

將值為x的新項追加到陣列的末尾。

array.pop([i])

從陣列中刪除索引為i的項並返回它。可選引數預設為-1,因此預設情況下會刪除並返回最後一項。

array.count(x)

返回數值中x出現的次數。

array.extend(iterable)

將可迭代物件(iterable)追加到陣列末尾。如果iterable是陣列,則必須具有相同的typecode,否則丟擲typeerror異常;如果不是數值,則必須是可迭代的,並且其元素型別與陣列型別相同。

array.insert(i,x)

在陣列下標i出插入元素x。

array.remove(x)

刪除陣列中第一次出現的x。

array.reverse()

反轉陣列元素位置。

array.index(x)

返回元素x在陣列中的最小下標。

array.frombytes(s)

將位元組擴充套件到陣列末尾。

array.fromfile(f,n)

從檔案物件 f中讀取n個專案(作為機器值)並將它們附加到陣列的末尾。如果可用的專案少於n個, 則會引發eoferror(read() didn』t return enough bytes),但可用的專案仍會插入到陣列中。

array.fromlist(list)

array.fromstring(s)

array.frombytes的別名。

array.fromunicode(s)

使用給定unicode字元擴充套件陣列,陣列typecode必須是』u』。

array.tobytes()

將陣列轉換為機器值陣列並返回位元組表示形式,與array.tofile()方法寫入檔案的位元組序列相同。

array.tofile(f)

將所以資料項以機器值寫入檔案物件f。

array.tolist()

將陣列轉換為具有相同項的普通列表

array.tostring()

array.tobytes的別名。

array.tounicode()

將陣列轉換為unicode字串。陣列必須是型別'u'陣列; 否則丟擲valueerror異常。

>>

>

import array

>>

> a = array.array(

'd')

#雙精度浮點陣列

>>

> a.extend([1

,2,3

,4,5

])#使用列表擴充套件陣列

>>

> a

array(

'd',

[1.0

,2.0

,3.0

,4.0

,5.0])

>>

> a.tobytes(

)#將陣列轉換為位元組

b'\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\x00@\x00\x00\x00\x00\x00\x00\x08@\x00\x00\x00\x00\x00\x00\x10@\x00\x00\x00\x00\x00\x00\x14@'

>>

> ac = a.tobytes(

)>>

> a.frombytes(ac)

#通過位元組擴充套件陣列

>>

> a

array(

'd',

[1.0

,2.0

,3.0

,4.0

,5.0

,1.0

,2.0

,3.0

,4.0

,5.0])

>>

> a.tounicode(

)#typecode非'u'無法使用tounicode

traceback (most recent call last)

: file ""

, line 1,in

a.tounicode(

)valueerror: tounicode(

) may only be called on unicode

type arrays

>>

> unic = array.array(

'u',

'hello'

)>>

> unic

array(

'u',

'hello'

)>>

> unic.tounicode(

)'hello'

>>

> unic.tolist()[

'h',

'e',

'l',

'l',

'o']

>>

>

python標準庫學習之zipfile模組

zipfile模組裡有兩個非常重要的class,分別是zipfile和zipinfo。zipfile是主要的類,用來建立和讀取zip檔案,而zipinfo是儲存的zip檔案的每個檔案的資訊的。class zipfile.zipfile file mode compression allowzip64...

Python標準庫系列之pathlib模組

首先我們看使用os模組連線目錄和檔案 import os.path data folder os.path.join source data text files file to open os.path.join data folder,raw data.txt f open file to op...

python標準庫 時間庫

眾所皆知,每乙個程式語言都有自己的時間類庫,python也不例外用法十分簡單 最基本的類,time類 time基本函式介紹 import time print time.asctime 如果未傳入乙個tuple或乙個time struct就是使用當前的時間,返回乙個24字長的時間字串 就這個mon ...