Fork me on GitHub

一 概念
如果我们需要一个只包含数字的列表,那么array.array比list更高效。数组支持所有跟可变序列有关的操作,包括.pop,.insert和.extend。
另外,数组还提供从文件读取和存入文件的更快的方法,如.frombytes和.tofile。
此模块定义了一种对象类型,可以紧凑地表示基本类型值的数组:字符、整数、浮点数等。 数组属于序列类型,其行为与列表非常相似,不同之处在于其中存储的对象类型是受限的。 类型在对象创建时使用单个字符的类型码来指定。 已定义的类型码如下:
 
二 内建函数
该模块提供了不少内建函数,具体名字和使用方法如下所示:
    append() -- append a new item to the end of the array
    buffer_info() -- return information giving the current memory info
    byteswap() -- byteswap all the items of the array
    count() -- return number of occurrences of an object
    extend() -- extend array by appending multiple elements from an iterable
    fromfile() -- read items from a file object
    fromlist() -- append items from the list
    frombytes() -- append items from the string
    index() -- return index of first occurrence of an object
    insert() -- insert a new item into the array at a provided position
    pop() -- remove and return item (default last)
    remove() -- remove first occurrence of an object
    reverse() -- reverse the order of the items in the array
    tofile() -- write all items to a file object
    tolist() -- return the array converted to an ordinary list
    tobytes() -- return the array converted to a string

 

 
三 实例解析
A.创建数组
import array

#creating array
int_array = array.array('i',[1,2,3,4])
float_array = array.array('f',[1.1,1.2,1.3,1.4])

print(int_array)
print(float_array)
print(type(int_array))
  

 

运行结果:
array('i', [1, 2, 3, 4])
array('f', [1.100000023841858, 1.2000000476837158, 1.2999999523162842, 1.399999976158142])
<class 'array.array'>
2 打印数组
  import array

int_array = array.array('i',[1,2,3,4])

for icnt in int_array:
    print(icnt)

for icnt in range(0,len(int_array)):
    print(f'int_array[{icnt}] = {int_array[icnt]}')

 

输出结果:
1
2
3
4
int_array[0] = 1
int_array[1] = 2
int_array[2] = 3

 

四 参考文档
posted on 2022-04-30 17:10  虚生  阅读(304)  评论(0编辑  收藏  举报