您的位置:首页 > 编程语言 > Python开发

python模块:array数组模块

2017-03-17 16:54 246 查看
http://blog.csdn.net/pipisorry/article/details/62889137

数组模块array简介

在Python中,列表是一个动态的指针数组,而array模块所提供的array对象则是保存相同类型的数值的动态数组。list的内存分析参考[python数据类型的内存分析 ]。

数组并不是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
皮皮blog

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

from: http://blog.csdn.net/pipisorry/article/details/62889137

ref: [
array
— Efficient arrays of numeric values
]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: