Python3中的zip()
-->the start
最近因为写程序的时候用到过zip()这个内建的方法,网上大多的介绍都是Python2版本的,很少有Python3版本的详细介绍。对于我这个在Python3下开始学习的菜鸟来说,确实是搞不太懂这其中的区别,所以花了我很长时间才算基本搞明白zip():
先来看官方的文档介绍吧:
Python2.7.11中
zip
([iterable, ...])
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. When there are multiple arguments which are all of the same length, zip()
is similar to map()
with an initial argument of None
. With a single sequence argument, it returns a list of 1-tuples. With no arguments, it returns an empty list.
The left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using zip(*[iter(s)]*n)
.
zip()
in conjunction with the *
operator can be used to unzip a list:
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> zipped
[(1, 4), (2, 5), (3, 6)]
>>> x2, y2 = zip(*zipped)
>>> x == list(x2) and y == list(y2)
True
New in version 2.0.
Changed in version 2.4: Formerly, zip()
required at least one argument and zip()
raised a TypeError
instead of returning an empty list.
Python3.5.1中:
zip
(*iterables)
Make an iterator that aggregates elements from each of the iterables.
Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The iterator stops when the shortest input iterable is exhausted. With a single iterable argument, it returns an iterator of 1-tuples. With no arguments, it returns an empty iterator. Equivalent to:
def zip(*iterables):
# zip('ABCD', 'xy') --> Ax By
sentinel = object()
iterators = [iter(it) for it in iterables]
while iterators:
result = []
for it in iterators:
elem = next(it, sentinel)
if elem is sentinel:
return
result.append(elem)
yield tuple(result)
The left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using zip(*[iter(s)]*n)
. This repeats the same iterator n
times so that each output tuple has the result of n
calls to the iterator. This has the effect of dividing the input into n-length chunks.
zip()
should only be used with unequal length inputs when you don’t care about trailing, unmatched values from the longer iterables. If those values are important, use itertools.zip_longest()
instead.
zip()
in conjunction with the *
operator can be used to unzip a list:
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> list(zipped)
[(1, 4), (2, 5), (3, 6)]
>>> x2, y2 = zip(*zip(x, y))
>>> x == list(x2) and y == list(y2)
True
从标黄的部分可以看出在Python3中zip()返回的是元祖组成的迭代器,而在Python2中返回的是元祖组成的列表。
从标红的部分可以看出在Python3中zip()解包的例子确实是让人理解不了。。。
我自己写了一个在Python3下面和在Python2下面的zip()的例子:
这样也许就能比较直观的看出zip()的用法吧。。。
再然后,有一天我看到了这么一行代码,我又搞不懂了:
如此Pythonic的用法,我这菜鸟真的搞不懂。再加上英文不过关,标绿的部分大概能看懂,还有对迭代器真的不理解。
<-- the end