流程python学习笔记:第二章(2)

 
数组:
在列表和元组中,存放的是具体的对象,如整数对象,字符对象。如下面的整数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的这个类型,是有符号的单字节整数,那么范围是-128127.如果我们插入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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序猿玩AI

你的鼓励是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值