In the Loop object and the function object, we understand the function of the loop (iterator). A loop is a container for an object that contains multiple objects. By invoking the next () method of the Loop (__next__ () method, in Python 3.x), the loop returns an object in turn. Until all objects are traversed, the loop will cite stopiteration errors.
In the for-I in iterator structure, each returned object of the loop is given to I until the loop ends. Using the ITER () built-in function, we can change containers such as tables and dictionaries into loops. Like what:
Copy Code code as follows:
For I in ITER ([2, 4, 5, 6]):
Print (i)
The Itertools package in the standard library provides a more flexible tool for generating loops. The input of these tools is mostly the existing loop device. On the other hand, these tools are completely free to use Python implementations, which simply provide a more standard and efficient way to implement them. This also conforms to the Python "only and best solution only" concept.
Copy Code code as follows:
# Import the Tools
From itertools Import *
Infinite loop device
Count (5, 2) #从5开始的整数循环器, increase each time by 2, that is 5, 7, 9, 11, 13, 15 ...
Cycle (' abc ') #重复序列的元素, both A, B, C, a, B, c ...
Repeat (1.2) #重复1.2, forming an infinite loop, i.e. 1.2, 1.2, 1.2, ...
Repeat can also have a limit of times:
Repeat (5) #重复10, repeated 5 times
Functional Tools
Functional programming is the programming paradigm of the function itself as a processing object. In Python, functions are also objects, so you can easily perform some functional processing, such as map (), filter (), and reduce () functions.
The itertools contains similar tools. These functions receive functions as arguments and return the result as a loop.
Like what:
Copy Code code as follows:
From itertools Import *
RLT = IMAP (POW, [1, 2, 3], [1, 2, 3])
For num in RLT:
Print (num)
The IMAP function is shown above. This function is similar to the map () function, except that it returns a loop instead of a sequence. Contains elements 1, 4, 27, i.e. 1**1, 2**2, 3**3 results. Function pow (the built-in exponentiation function) as the first argument. Pow (), in turn, acts on each element of the following two lists and collects the function results, which form the returned loop.
In addition, you can use the following function:
Copy Code code as follows:
Starmap (POW, [(1, 1), (2, 2), (3, 3)])
POW will act on each tuple of the table in turn.
The IFilter function is similar to the filter () function, except that it returns a loop.
Copy Code code as follows:
IFilter (lambda x:x > 5, [2, 3, 5, 6, 7]
The lambda function is applied to each element in turn, and if the function returns True, the original element is collected. 6, 7
Furthermore
Copy Code code as follows:
Ifilterfalse (lambda x:x > 5, [2, 3, 5, 6, 7])
Similar to the above, but collects elements that return false. 2, 3, 5
Copy Code code as follows:
TakeWhile (Lambda x:x < 5, [1, 3, 6, 7, 1])
When the function returns True, the element is collected to the loop. Once the function returns false, it stops. 1, 3
Copy Code code as follows:
Dropwhile (Lambda x:x < 5, [1, 3, 6, 7, 1])
When the function returns False, the element is skipped. Once the function returns True, it starts collecting all remaining elements into the loop. 6, 7, 1.
Combination Tools
We can get a new loop by combining the original loop device.
Copy Code code as follows:
Chain ([1, 2, 3], [4, 5, 7]) # Connect two loops into one. 1, 2, 3, 4, 5, 7
Product (' abc ', [1, 2]) # The Cartesian product of multiple loop sets. Equivalent to nested loops
For M, N in product (' abc ', [1, 2]):
Print m, n
Permutations (' abc ', 2) # Select two elements from ' ABCD ', such as AB, BC, ... Sorts all the results, returning to the new loop.
Note that the above combination is in the order that AB and BA are returned.
Combinations (' abc ', 2) # Select two elements from ' ABCD ', such as AB, BC, ... Sorts all the results, returning to the new loop.
Note that the above combination is not in order, that is, AB, Ba words, only return a AB.
Combinations_with_replacement (' abc ', 2) # is similar to the above, but allows two selected elements to be duplicated. That's more AA, BB, CC.
GroupBy ()
The key function is applied to each element of the original loop. According to the result of the key function, the element with the same function result is divided into a new loop device. Each new loop takes a function to return the result as a label.
It's like the height of a group of people as a revolving device. We can use a key function that returns "tall" if the height is greater than 180, and returns "short" if the height is at 160, and returns "middle" in the middle. Eventually, all height will be divided into three loops, namely "tall", "short", "Middle".
Copy Code code as follows:
def height_class (h):
If h > 180:
Return "Tall"
Elif H < 160:
Return ' short '
Else
Return "middle" friends = [191, 158, 159, 165, 170, 177, 181,, 190] friends = sorted (friends, key = Height_class)
For M, N in GroupBy (friends, key = Height_class):
Print (m)
Print (list (n))
Note that the GroupBy function is similar to the Uniq command in UNIX. Before grouping, you need to use sorted () on the elements of the original loop, sorted according to the key function, and let the same group of elements move closer to the position first.
Other tools
Compress (' ABCD ', [1, 1, 1, 0]) # According to the true and false values of [1, 1, 1, 0], select the element in the first parameter ' ABCD '. A, B, C
Islice () # is similar to the slice () function, but returns a loop
Izip () # is similar to the zip () function, but returns a loop.
Summarize
Itertools tools can be implemented on their own. Itertools only provides a more formed solution.