Python built-in functions (67) -- zip, python built-in 67zip
English document:
zip
(* Iterables)
Make an iterator that aggregates elements from each of the iterables.
Returns an iterator of tuples, whereI-Th tuple containsI-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.
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 usingzip(*[iter(s)]*n)
. This repeatsSameIteratorn
Times so that each output tuple has the resultn
Callto the iterator. This has the effect of dividing the input into n-length chunks.
Note:
1. The function aggregates elements at the same position in each iterator passed in, and returns a new tuple type iterator.
>>> X = [, 3] >>> y = [, 6] >>>> xy = zip (x, y) >>> xy # the xy type is zip. <zip object at 0x0429C828> # import Iterable >>> from collections import Iterable >>> isinstance (xy, Iterable) # determine whether objects can be iterated: True >>> list (xy) # result [(1, 4), (2, 5), (3, 6)]
2. if the length of the introduced iterator is inconsistent, the iterator with the shortest length stops aggregation after iteration.
>>> X = [, 3] # length 3 >>> y = [, 8] # Length 5 >>> list (zip (x, y )) # minimum length 3 [(1, 4), (2, 5), (3, 6)]
3. If only one iterator is input, the iterator of the single element tuples returned.
>>> list(zip([1,2,3]))[(1,), (2,), (3,)]
4. If no parameter is input, an empty iterator is returned.
>>> list(zip())[]
5. zip (* [iter (s)] * n) is equivalent to calling zip (iter (s), iter (s),..., iter (s )).
>>> x = [1,2,3]>>> list(zip(*[x]*3))[(1, 1, 1), (2, 2, 2), (3, 3, 3)]>>> list(zip(x,x,x))[(1, 1, 1), (2, 2, 2), (3, 3, 3)]