This article introduces the itertools module in Python.
Itertools module: iterator
1. infinite loop: count, cycle, repeat
(1) count (5, 3) # increase the number of integers starting from 5 by 3, namely, 5, 8, 11, 14, 17... from itertools import * import timea = count (5, 3) for I in a: print (I) time. sleep (1) output: 58111417202326
(2) cycle ('zxy') # Repeat element x y z... from itertools import * import times = cycle ('XYZ') for I in s: print (I) time. sleep (1) output result: xyzxyzxyz
Repeat () # repeat element Example 1: from itertools import * import times = repeat (3.14) # infinite repeat element for I in s: print (I) time. sleep (1) output result: 3.143.143.143.143.14 Example 2: from itertools import * import times = repeat () # repeat element 3, 5 times in total for I in s: print (I) time. sleep (1) output: 33333
2. functional tools: starmap, takewhile, and dropwhile
(1) starmap () # similar to map, from itertools import * s = starmap (pow, [(), (), ()]) # pow () returns 1427 (2) takewhile () as the output result of the index 1 ** 2 ** 3 for I in s: print (I) # When the function returns True, collect elements to the iterator. Once the function returns False, it stops. From itertools import * s1 = takewhile (lambda x: x <5, [, 7]) for I in s1: print (I) the output result is: 1234 (3) dropwhile () # opposite to takewhile. S2 = dropwhile (lambda x: x <5, [567, 7]) for I in s2: print (I) output result:
The above is a detailed description of the itertools module in Python. For more information, see other related articles in the first PHP community!