Introduction of Circulator itertools in Python

  • 2021-11-30 00:27:11
  • OfStack

Directory 1, Infinite Circulator 2, Functional Tools 3, Combination Tools 4, groupby () 5, Other Tools

In the for i in iterator structure, the object returned by the circulator is assigned to i each time until the end of the loop. Using the iter () built-in function, we can turn containers such as tables and dictionaries into loops. For example


for i in iter([2, 4, 5, 6]):
    print(i)


In the standard library itertools Package provides a more flexible tool for generating loops. Most of the inputs to these tools are existing circulators. On the other hand, these tools can be implemented by themselves using Python, which only provides a relatively standard and efficient implementation method. This is also in line with Python's concept of "only and preferably only solutions".


# import the tools
from itertools import *


1. Infinite circulator

count(5, 2)    # Integer loops that start with 5 and add 2 at a time, i.e. 5, 7, 9, 11, 13, 15... cycle('abc')   a, b, c, a, b, c... repeat(1.2)   # Repeat 1.2 to form an infinite loop, i.e. 1.2, 1.2, 1.2,...

repeat can also have a limit of 1 times:

repeat(10, 5)  # Repeat 10 for 5 times

2. Functional tools

Functional programming is a programming paradigm that takes the function itself as the processing object. In Python, functions are also objects, so it is easy to handle some functional expressions, such as map (), filter () and reduce () functions.

itertools includes similar tools. These functions take functions as arguments and return the result as a loop.

For example:


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 instead of a sequence, it returns a loop. Contains the results of elements 1, 4, 27, that is, 1**1, 2**2, 3**3. Function pow (built-in power function) as the first parameter. pow () acts on each element of the next two lists in turn and collects the results of the function to form a loop that returns.

In addition, you can use the following functions:

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.


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

In addition,

ifilterfalse(lambda x: x > 5, [2, 3, 5, 6, 7])

Similar to the above, but collects elements that return False. 2, 3, 5

takewhile(lambda x: x < 5, [1, 3, 6, 7, 1])

When the function returns True, the elements are collected into the circulator. If the 1-denier function returns False, it stops. 1, 3

dropwhile(lambda x: x < 5, [1, 3, 6, 7, 1])

When the function returns False, the element is skipped. The 1 denier function returns True, then all remaining elements are collected into the circulator. 6, 7, 1

3. Combination Tools

We can get a new circulator by combining the original circulators.

chain([1, 2, 3], [4, 5, 7])    # Connect two loops into one. 1, 2, 3, 4, 5, 7 count(5, 2)   0 # Cartesian product of multiple sets of circulators. Equivalent to nested loops

for m, n in product('abc', [1, 2]):
    print m, n
 

permutations('abc', 2)   # Pick two elements from 'abcd', such as ab, bc,... Sort all the results and return them as new loops.

Note: The above combinations are sequenced, that is, ab and ba both return.

combinations('abc', 2)  # Pick two elements from 'abcd', such as ab, bc,... Sort all the results and return them as new loops.

Note: The above combinations are in no order, that is, ab and ba, only one ab is returned.

combinations_with_replacement('abc', 2) # Similar to above, but allows duplication of selected elements twice. That is, there are more aa, bb and cc

4. groupby ()

The key function is applied to each element of the original circulator. According to the key function result, the elements with the same function result are divided into a new circulator. Each new loop is labeled with the result returned by the function.

It's like the height of a group of people acting as a circulator. We can use this one key function: if the height is greater than 180, return "tall"; If the height is below 160, return "short"; The middle returns "middle". Eventually, all heights will be divided into three circulators, namely "tall", "short" and "middle".


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, 182, 190]

friends = sorted(friends, key = height_class)
for m, n in groupby(friends, key = height_class):
    print(m)
    print(list(n))

Note: The function of groupby is similar to the uniq command in UNIX. Before grouping, you need to use sorted () to sort the elements of the original circulator according to key function, so that the elements of the same group are close in position first.

5. Other tools

compress('ABCD', [1, 1, 1, 0])  # Select the element in the first parameter 'ABCD' based on the true or false values of [1, 1, 1, 0]. A, B, C islice() # Similar to the slice () function except that it returns a loop izip()  # Similar to the zip () function, except that it returns a loop.

Summary:
The tools of itertools can be implemented by themselves. itertools just provides a more shaped solution.


Related articles: