详解Python中的array数组模块相关使用

yipeiwu_com6年前Python基础

初始化
array实例化可以提供一个参数来描述允许那种数据类型,还可以有一个初始的数据序列存储在数组中。

import array
import binascii
s = 'This is the array.'
a = array.array('c', s)
print 'As string:', s
print 'As array :', a
print '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 array
import pprint
a = array.array('i', xrange(3))
print 'Initial :', a
a.extend(xrange(3))
print 'Extended:', a
print '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 array
import binascii
import tempfile

a = array.array('i', xrange(5))
print 'A1: ',a
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中循环处理数据高效的多。   

>>> ================================ 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

相关文章

用python中的matplotlib绘制方程图像代码

用python中的matplotlib绘制方程图像代码

import numpy as np import matplotlib.pyplot as plt def main(): # 设置x和y的坐标范围 x=np.aran...

Python paramiko模块的使用示例

paramiko模块提供了ssh及sft进行远程登录服务器执行命令和上传下载文件的功能。这是一个第三方的软件包,使用之前需要安装。 1 基于用户名和密码的 sshclient 方式登录...

django框架ModelForm组件用法详解

django框架ModelForm组件用法详解

本文实例讲述了django框架ModelForm组件用法。分享给大家供大家参考,具体如下: ModelForm组件是django中一个非常强大的组件,其功能主要有 一 校验字段 Mode...

python中stdout输出不缓存的设置方法

考虑以下python程序:复制代码 代码如下:#!/usr/bin/env pythonimport syssys.stdout.write("stdout1 ")sys.stderr....

python中open函数的基本用法示例

前言 本文主要介绍的是关于python中open函数用法的相关资料,用法如下: name = open('errname.txt','w')<br>name.readli...