码迷,mamicode.com
首页 > 其他好文 > 详细

zip、izip、izip_longest的区别

时间:2016-10-10 19:12:12      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:

  昨儿,小爷在LeetCode上刷了一道题,关于把两个字符串型的整数加和的问题(当然不能直接强转),链接在这https://leetcode.com/problems/add-strings/,感兴趣的朋友们可以一试,不难,只要想做肯定做得出,无非就是要想想进位和哪个字符串位数多的问题,提交几次考虑的情况就全面了。

  说来简单,小爷还是做了两个小时,没刷过题真的是不行,短炼。

  小爷用的是Python,写了百十来行,用了 一系列if,else。然而,当去欣赏大牛们的代码时,没想着优化,就是本着能做出来的态度的小爷我还是震惊了,人家就用了7行!!

  那么,对于小爷这样一个好学的孩子,怎么能放过这样一个学习的机会,在此记录一下。

  主要就是zip、izip和izip_longest的用法。

  • zip(build-in方法)

文档中这样描述:

  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. 

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

举个栗子:

In [27]: a = [‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘]

In [28]: b = range(10)

In [29]: zip(a,b)
Out[29]: [(‘a‘, 0), (‘b‘, 1), (‘c‘, 2), (‘d‘, 3), (‘e‘, 4)]
注意这里返回的是列表,且列表的长度依赖于输入元组中较短的一个
  • 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。

如果输入的两个序列都是特别大的情况,zip就会很慢了。使用izip比较下。(因为返回的是一个迭代器,并且同步迭代,所以速度比较快。

In [30]: a = range(10000000)

In [31]: b = range(10000000)

In [32]: tim
%%timeit %time    %timeit

In [32]: %timeit(zip(a,b))
1 loops, best of 3: 811 ms per loop

In [33]: import itertools

In [34]: %timeit(itertools.izip(a,b))
1000000 loops, best of 3: 349 ns per loop
  • 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来制定那些缺失值的默认值

举个栗子:

In [35]: a = [‘a‘,‘b‘,‘c‘]

In [36]: b = range(10)

In [37]: itertools.izip_longest(a,b,fillvalue=-1)
Out[37]: <itertools.izip_longest at 0x250e540>

In [38]: c = itertools.izip_longest(a,b,fillvalue=-1)

In [42]: for i in c:
  ....:	  print i
  ....:
(‘a‘, 0)
(‘b‘, 1)
(‘c‘, 2)
(-1, 3)
(-1, 4)
(-1, 5)
(-1, 6)
(-1, 7)
(-1, 8)
(-1, 9)

  此外,牛人的方法里还用了ord(),这个之前也没见过,该函数和chr()对应,是将ascii字符转换成对应的整数值,而chr()是将整数值转换成对应的ascii字符。
举个栗子:
>>> print chr(48), chr(49), chr(97)
0 1 a

>>> print ord(‘a‘), ord(‘0‘), ord(‘1‘)
97 48 49

  至此,牛人的方法就能理解了。
 

zip、izip、izip_longest的区别

标签:

原文地址:http://www.cnblogs.com/LuffySir/p/5946392.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!