concern
You want to iterate through multiple sequences at the same time, each time taking an element from one sequence separately.
prescription
To iterate through multiple sequences at once, use the zip() function. For example:
>>> xpts = [1, 5, 4, 2, 10, 7] >>> ypts = [101, 78, 37, 15, 62, 99] >>> for x, y in zip(xpts, ypts): ... print(x,y) ... 1 101 5 78 4 37 2 15 10 62 7 99 >>>
zip(a, b) generates an iterator that returns the tuple (x, y), where x is from a and y is from b. Once one of the sequences ends at the bottom, the iteration ends. The length of the iteration is therefore the same as the length of the shortest sequence in the argument.
>>> a = [1, 2, 3] >>> b = ['w', 'x', 'y', 'z'] >>> for i in zip(a,b): ... print(i) ... (1, 'w') (2, 'x') (3, 'y') >>>
If this is not the effect you want, then you can also use the itertools.zip_longest() function instead. For example:
>>> from itertools import zip_longest >>> for i in zip_longest(a,b): ... print(i) ... (1, 'w') (2, 'x') (3, 'y') (None, 'z')
>>> for i in zip_longest(a, b, fillvalue=0): ... print(i) ... (1, 'w') (2, 'x') (3, 'y') (0, 'z') >>>
talk over
The zip() function is useful when you want to process data in pairs. For example, suppose you head a list and a list of values, like the following:
headers = ['name', 'shares', 'price'] values = ['ACME', 100, 490.1]
Using zip() allows you to package them and generate a dictionary:
s = dict(zip(headers,values))
Or you can generate output like the following:
for name, val in zip(headers, values): print(name, '=', val)
Although not common, zip() can take more than two sequences as arguments. The resulting tuple has the same number of elements as the input sequence. For example;
>>> a = [1, 2, 3] >>> b = [10, 11, 12] >>> c = ['x','y','z'] >>> for i in zip(a, b, c): ... print(i) ... (1, 10, 'x') (2, 11, 'y') (3, 12, 'z') >>>
One final point to emphasize is that zip() creates an iterator to be returned as the result. If you need to store the paired values in a list, use the list() function. For example:
>>> zip(a, b) <zip object at 0x1007001b8> >>> list(zip(a, b)) [(1, 10), (2, 11), (3, 12)] >>>
Above is the detailed content of the method of Python iterate multiple sequences at the same time, more information about Python iterate multiple sequences at the same time please pay attention to my other related articles!