Python中的数组

来源:互联网 发布:mac怎么使用投影仪 编辑:程序博客网 时间:2024/06/03 18:38

1 数组的创建:

涉及的module: array

 

An array object is similar to a list except that it can hold only certain types of simple data and only one type at any given time. when you create an array object,you specify which type of data it will hold:

 

>>> import array
>>> z=array.array('B')
>>> z.append(5)
>>> z
array('B', [5])
>>> z[0] 
5
>>> q= array.array('i',[5,10,20])
>>> q
array('i', [5, 10, 20])
>>> q[0] 
5

 

数组支持的数据类型:

 

求数组的长度:

arrayname.itemsize;

>>> q.itemsize
4

 

数组和list 之间转换:

数组转换为list:toList(): converts the array to an ordinary list

>>> q.tolist()
[5, 10, 20]

 

将一个list添加到数组的末尾:

>>> q
array('i', [5, 10, 20])
>>> q.fromlist([3,4])
>>> q
array('i', [5, 10, 20, 3, 4])

 

array 和string之间的相互转换:

tostring():onvert an array to a sequence of bytes using the tostring() methond.

fromstring():taking a string of bytes and converting them to values for the array

 

数组和文件之间的互操作:

tofile(file):convert the array to a sequence of bytes and writes the resulting bytes to a file you pass in

fromfiles(file,count): reads the specifiled number of items in from a file object and appends them to the array.

 

原创粉丝点击