详解Python中的array数组模块相关使用
发布时间:2020-12-16 20:31:34 所属栏目:Python 来源:网络整理
导读:初始化 array实例化可以提供一个参数来描述允许那种数据类型,还可以有一个初始的数据序列存储在数组中。 import arrayimport binasciis = 'This is the array.'a = array.array('c',s)print 'As string:',sprint 'As array :',aprint 'As hex :',binascii.h
初始化 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
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',2,2]) slice: : array('i',[2,1]) Itetator: [(0,0),(1,1),(2,2),(3,(4,(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
候选字节顺序 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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- 基于PyQt5的Python-Gui开发
- python-如何收缩NetworkX中只有2条边的节点?
- cors是什么?django中怎么解决这个问题?
- 如何基于Python + requests实现发送HTTP请求
- python – pymongo:MongoClient或Connection
- 创建带有元数据头的csv文件,后跟Python / Pandas中的时间序
- python – 使用PyCrypto解密带有RSA公钥的消息
- python – 长度为k的非重叠子串的随机抽样
- Python SSLError:客户端错误(EOF发生违反协议),服务器端错
- Note that only Django core commands are listed as setti