1. 程式人生 > >python模組:array陣列模組

python模組:array陣列模組

陣列模組array簡介

在Python中,列表是一個動態的指標陣列,而array模組所提供的array物件則是儲存相同型別的數值的動態陣列。list的記憶體分析參考[ ]。

陣列並不是Python中內建的標配資料結構,不過擁有array模組我們也可以在Python中使用陣列結構。

python 有提供一個array模組,用於提供基本數字,字元型別的陣列。用於容納字元號,整型,浮點等基本型別。這種模組主要用於二進位制上的緩衝區,流的操作。

資料型別

Type codeC TypePython TypeMinimum size in bytesNotes
'b'signed charint1
'B'unsigned charint1
'u'Py_UNICODEUnicode character2(1)
'h'signed shortint2
'H'unsigned shortint2
'i'signed intint2
'I'unsigned intint2
'l'signed longint4
'L'unsigned longint4
'q'signed long longint8(2)
'Q'unsigned long longint8(2)
'f'floatfloat4
'd'doublefloat8
Note: 這裡只是規定了對應的最小位元組,而不是真實佔用的記憶體位元組數!!!如lz使用的64位機測試的'i'對應的位元組數為4而不是2(32位機才是2吧可能)!

In[4]: a = array.array('i')
In[5]: a.__sizeof__()
64
In[6]: a = array.array('i', [1])
In[7]: a.__sizeof__()
68

In[10]: a.itemsize
4

array模組的使用

初始化

array例項化可以提供一個引數來描述允許那種資料型別,還可以有一個初始的資料序列儲存在陣列中。
陣列配置為包含一個位元組序列,用一個簡單的字串初始化。

class array.array(typecode[, initializer])

A new array whose items are restricted by typecode, and initializedfrom the optional initializer value, which must be a list, abytes-like object, or iterable over elements of theappropriate type.

If given a list or string, the initializer is passed to the new array’sfromlist(), frombytes(), or fromunicode() method (see below)to add initial items to the array. Otherwise, the iterable initializer ispassed to the extend() method.

import array
s = 'This is the array.'
a = array.array('c', s)
print 'As array :', a

As array : array('c', 'This is the array.')

陣列操作

類似於其他python序列,可以採用同樣方式擴充套件和處理array。支援的操作包括分片,迭代以及向末尾增加元素。

建立一個interger型別的陣列

myarr = array(’i‘)  <——–建立陣列

myarr.append(3)   <——–追加元素

取陣列的值,通過下標
num1 = myarr[0]   <———–第一個值

刪除最後一個
myarr.pop()
刪除第一個指定的X
myarr.remove(x)
指定位置,插入值
myarr.insert(6,10)
6表示下標,10表示要插入的值
陣列反序
myarr.reverse()

array.count(x)

    Return the number of occurrences of x in the array.
array.itemsize
    The length in bytes of one array item in the internal representation.
array.index(x)
    Return the smallest i such that i is the index of the first occurrence of x in the array.


import array
a = array.array('i', xrange(3))
print 'Initial :', a
a.extend(xrange(3))
print 'Extended:', a
print 'slice: :', a[2:5]

Initial : array('i', [0, 1, 2])
Extended: array('i', [0, 1, 2, 0, 1, 2])
slice: : array('i', [2, 0, 1])

陣列和檔案輸入輸出

可以使用高效讀/寫檔案的專用內建方法將陣列的內容寫入檔案或從檔案讀取陣列。
import array
import binascii
import tempfile
a = array.array('i', xrange(5))
output = tempfile.NamedTemporaryFile()
a.tofile(output.file)
output.flush

with open(output.name, 'rb') as input:
  raw_input = input.read()
  print 'Raw Contents:', binascii.hexlify(raw_data)
  input.seek(0)
  a2 = array.array('i')
  a2.fromfile(input, len(a))
  print 'A2: ', a2

候選位元組順序

如果陣列中的資料沒有采用固有的位元組順序,或者在傳送到一個採用不同位元組順序的系統前需要交換順序,可以在python轉換整個陣列而無須迭代處理每個元素。
import array
import binascii
def to_hex(a):
  chars_per_item = a.itemsize * 2
  hex_version = binascii.hexlify(a)
  num_chunks = len(hex_version) / chars_per_item
  for i in xrange(num_chunks):
    start = i * chars_per_item
    end = start + chars_per_item
    yield hex_version[start:end]
a1 = array.array('i', xrange(5))
a2 = array.array('i', xrange(5))
a2.byteswap()
fmt = '%10s %10s %10s %10s'
print fmt % ('A1_hex', 'A1', 'A2_hex', 'A2')
print fmt % (('-' * 10,) * 4)
for value in zip(to_hex(a1), a1, to_hex(a2), a2):
  print fmt % value
byteswap()會交換C陣列中元素的位元組順序,比在python中迴圈處理資料高效的多。
  A1_hex     A1   A2_hex     A2
---------- ---------- ---------- ----------
 00000000     0  00000000     0
 01000000     1  00000001  16777216
 02000000     2  00000002  33554432
 03000000     3  00000003  50331648
 04000000     4  00000004  67108864