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)
既然没人写这个函数,那我就从官方文档抠出来翻译一下。
后来演变成了python3自带的函数,特别注意能够处理迭代的特性
操作很简单,就是顺序对应打包,数目不一致就尽可能多的取前面能打包的匹配。
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