python中zip 和 izip , izip_longest比较

zip是build-in方法

而izip是itertools中的一个方法


这两个方法的作用是相似的,但是具体使用中有什么区别呢?今天来探究一下。

zip

文档中这样描述:

This function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The returned list is truncated in length to the length of the shortest argument sequence.

就是把多个序列或者是迭代器的元素,组合成元组。返回的元组的长度是所有输入序列中最短的

[python]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. In [27]: a = ['a''b''c''d''e']  
  2.   
  3. In [28]: b = range(10)  
  4.   
  5. In [29]: zip(a,b)  
  6. Out[29]: [('a'0), ('b'1), ('c'2), ('d'3), ('e'4)]  

组合之后的元组长度是依照两个输入序列中最短的a为准的。


如果输入的两个序列都是特别大的情况,zip就会很慢了。使用izip比较下。

[python]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. In [30]: a = range(10000000)  
  2.   
  3. In [31]: b = range(10000000)  
  4.   
  5. In [32]: tim  
  6. %%timeit %time    %timeit  
  7.   
  8. In [32]: %timeit(zip(a,b))  
  9. 1 loops, best of 3811 ms per loop  
  10.   
  11. In [33]: import itertools  
  12.   
  13. In [34]: %timeit(itertools.izip(a,b))  
  14. 1000000 loops, best of 3349 ns per loop  

这样看izip会快的多。


izip

文档中的描述:

Make an iterator that aggregates elements from each of the iterables. Like zip() except that it returns an iterator instead of a list. Used for lock-step iteration over several iterables at a time.

把不同的迭代器的元素聚合到一个迭代器中。类似zip()方法,但是返回的是一个迭代器而不是一个list。用于同步迭代一次几个iterables

orangleliu: 因为返回的是一个迭代器,并且同步迭代,所以速度比较快。


izip_longest

Make an iterator that aggregates elements from each of the iterables. If the iterables are of uneven length, missing values are filled-in with fillvalue. Iteration continues until the longest iterable is exhausted

也就是说这个zip方法使用izip一样的原理,但是会使用最长的迭代器来作为返回值的长度,并且可以使用fillvalue来制定那些缺失值的默认值

[python]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. In [35]: a = ['a','b','c']  
  2.   
  3. In [36]: b = range(10)  
  4.   
  5. In [37]: itertools.izip_longest(a,b,fillvalue=-1)  
  6. Out[37]: <itertools.izip_longest at 0x250e540>  
  7.   
  8. In [38]: c = itertools.izip_longest(a,b,fillvalue=-1)  
  9.   
  10. In [42]: for i in c:  
  11.    ....:     print i  
  12.    ....:  
  13. ('a'0)  
  14. ('b'1)  
  15. ('c'2)  
  16. (-13)  
  17. (-14)  
  18. (-15)  
  19. (-16)  
  20. (-17)  
  21. (-18)  
  22. (-19)  


探究一下,基本的区别就是这些,具体的使用要看具体的编程场景。


原文链接:http://blog.csdn.net/orangleliu/article/details/23737701?utm_source=tuicool&utm_medium=referral

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值