Smooth python and cookbook Study Notes (6), pythoncookbook
1. iterate multiple sequences at the same time (zip (function ))
You can use the zip () function to iterate multiple sequences at the same time.
>>> X = [1, 2, 3, 4, 5, 6]>>> Y = [121, 223, 116, 666, 919, 2333]>>> for x, y in zip(X, Y):... print(x, y)...1 1212 2233 1164 6665 9196 2333
Zip (a, B) is used to create an iterator that generates tuples (x, y), x is taken from sequence a, and y is taken from sequence B. When, when no element in sequence B can continue iteration, the entire iteration process ends.
>>> a = [1, 2, 3, 4, 5, 6]>>> b = ['x', 'y', 'z']>>> for x, y in zip(a, b):... print(x, y)...1 x2 y3 z>>>
Itertools.zip _ longest () can be used if you want to iterate over the redundant sequence, that is, elements 4, 5, and 6 in ().
>>> A = [1, 2, 3, 4, 5, 6] >>> B = ['x', 'y ', 'Z'] >>> from itertools import zip_longest >>> for I in zip_longest (a, B ):... print (I )... (1, 'x') (2, 'y') (3, 'z') (4, None) # None (5, None) (6, none) >>> for I in zip_longest (a, B, fillvalue = 2): # You can specify the value of the redundant element... print (I )... (1, 'x') (2, 'y') (3, 'z') (4, 2) # specify the value of the redundant element as 2 (5, 2) (6, 2)
The zip () function can also accept two additional sequences, which are used in the same way as the two sequences.
2. iterate in different containers
The itertools. chain () method can be used to iterate objects in different containers. Chain is more efficient, elegant, and pythonic than merging a and B before iteration.
>>> from itertools import chain>>> a = [1, 2, 3, 4, 5]>>> b = ['x', 'y', 'z']>>> for i in chain(a, b):... print(i)...12345xyz
3. Merge multiple ordered sequences and iterate the entire ordered sequence.
Merge multiple ordered sequences and iterate the entire ordered sequence. You can use the module heapq and the heapq. merge () function. Note that the sequence must be ordered.
>>> from heapq import merge>>> a = [1, 3, 4, 5, 7, 9]>>> b = [2, 6, 8, 11, 13]>>> for i in merge(a, b):... print(i)...1234567891113