数组:
在列表和元组中,存放的是具体的对象,如整数对象,字符对象。如下面的整数b。占据12个字节。因为存放的是整数对象,而非整数本身
b=1 print sys.getsizeof(b)
E:\python2.7.11\python.exe E:/py_prj/fluent_python/chapter2.py
12
对于存放大量数据来说。我们选择用数组的形式要好很多。因为数组存储的不是对象,而是数字的机器翻译。也就是字节表述。和C语言中的数组是一个道理
在array中需要规定各个字符的类型,如上表中的Type code。定义好类型后则数组内的元素必须全是这个类型,否则会报错。就像下面的代码。类型规定的是b也就是单字节的整数。但是在插入的时候却是字符,则报错:TypeError: an integer is required
num=array('b') num.append('c')
E:\python2.7.11\python.exe E:/py_prj/fluent_python/chapter2.py
Traceback (most recent call last):
File "E:/py_prj/fluent_python/chapter2.py", line 18, in <module>
num.append('c')
TypeError: an integer is required
在上表中,每个类型都有字节大小的限制。如果超出了字节大小的限制也是会报错的。还是b的这个类型,是有符号的单字节整数,那么范围是-128到127.如果我们插入128.则报错:signed char is greater than maximum 提示超过了最大
num=array('b') num.append(128)
E:\python2.7.11\python.exe E:/py_prj/fluent_python/chapter2.py
Traceback (most recent call last):
File "E:/py_prj/fluent_python/chapter2.py", line 18, in <module>
num.append(128)
OverflowError: signed char is greater than maximum
对于数组这种结构体来说,由于占用的内存小,因此在读取和写入文件的时候的速度更快,相比于列表来说的话。下面来对比下:
首先是用列表生成并写入txt文档的用法
def arry_try_list(): floats=[float for float in range(10**7)] fp=open('list.txt','wb') start=time.clock() for f in floats: fp.write(str(f)) fp.close() end=time.clock() print end-start
E:\python2.7.11\python.exe E:/py_prj/fluent_python/chapter2.py
7.83854664189
总共耗时了7秒
再来看数组的形式:
def array_try(): floats=array('d',(random() for i in range(10**7))) start=time.clock() fp=open('floats.bin','wb') floats.tofile(fp) fp.close() end=time.clock() print end-start
E:\python2.7.11\python.exe E:/py_prj/fluent_python/chapter2.py
0.883260677006
耗时0.88秒。速度提高了9倍
再来对比下写入的速度:
def array_try(): floats=array('d') start=time.clock() fp=open('floats.bin','rb') floats.fromfile(fp,10**7) fp.close() end=time.clock() print end-start
E:\python2.7.11\python.exe E:/py_prj/fluent_python/chapter2.py
0.0515373089318
数组的方式只用了0.05秒,也是非常的快
双向队列
在列表或者数组中,可以用append,pop来模拟栈或者队列的操作。本章作者介绍了双向队列,在进行数组的移动时更为高效
dq=deque(range(10),maxlen=10) print dq
deque([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], maxlen=10) dq.rotate(3) #将最右边的3个元素移到左边 print dq
deque([7, 8, 9, 0, 1, 2, 3, 4, 5, 6], maxlen=10) dq.rotate(-3) #将最左边的3个元素移到右边 print dq
deque([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], maxlen=10) num=dq.popleft() #最左边的元素移除 print dq
deque([1, 2, 3, 4, 5, 6, 7, 8, 9], maxlen=10) dq.appendleft(num) #将元素插入到最左边 print dq
deque([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], maxlen=10)