詳解Python中的array數組模組相關使用

來源:互聯網
上載者:User
初始化
array執行個體化可以提供一個參數來描述允許那種資料類型,還可以有一個初始的資料序列儲存在數組中。

import arrayimport binasciis = 'This is the array.'a = array.array('c', s)print 'As string:', sprint 'As array :', aprint 'As hex  :', binascii.hexlify(a)

數組配置為包含一個位元組序列,用一個簡單的字串初始化。

>>> ================================ RESTART ================================>>> As string: This is the array.As array : array('c', 'This is the array.')As hex  : 54686973206973207468652061727261792e


處理數組
類似於其他python序列,可以採用同樣方式擴充和處理array。

import arrayimport pprinta = array.array('i', xrange(3))print 'Initial :', aa.extend(xrange(3))print 'Extended:', aprint 'slice: :', a[2:5]print 'Itetator:'print list(enumerate(a))

支援的操作包括分區,迭代以及向末尾增加元素。

>>> ================================ RESTART ================================>>> Initial : array('i', [0, 1, 2])Extended: array('i', [0, 1, 2, 0, 1, 2])slice: : array('i', [2, 0, 1])Itetator:[(0, 0), (1, 1), (2, 2), (3, 0), (4, 1), (5, 2)]


數組和檔案
可以使用高效讀/寫檔案的專用內建方法將數組的內容寫入檔案或從檔案讀取數組。

import arrayimport binasciiimport tempfilea = array.array('i', xrange(5))print 'A1: ',aoutput = tempfile.NamedTemporaryFile()a.tofile(output.file)output.flushwith 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 arrayimport binasciidef 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中迴圈處理資料高效的多。

>>> ================================ RESTART ================================>>>   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
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.