Introduction to itertools in The Python Standard Library

Source: Internet
Author: User
Tags imap
This article mainly introduces itertools in the Python standard library. This article describes infinite loops, functional tools, combination tools, groupby (), and other tools, for more information about the functions of the iterator, see loop objects and function objects. A iterator is a container of objects and contains multiple objects. By calling the next () method (_ next _ () method of the loop Generator in Python 3. x), the loop Generator returns an object in sequence. Until all object traversal is exhausted, the iterator will cite the StopIteration error.

In the for I in iterator structure, the object returned by the iterator is assigned to I every time until the loop ends. Using the iter () built-in function, we can change containers such as tables and dictionaries into a iterator. For example:

The code is as follows:


For I in iter ([2, 4, 5, 6]):
Print (I)

The itertools package in the standard library provides a more flexible tool to generate the iterator. The input of these tools is mostly an existing iterator. On the other hand, these tools can be fully implemented by themselves using Python. this package only provides a standard and efficient implementation method. This is also in line with the concept of "only and preferably only solutions" in Python.

The code is as follows:


# Import the tools
From itertools import *

Infinite loop device

Count (5, 2) # An integer iterator starting from 5, adding 2 at a time, that is, 5, 7, 9, 11, 13, 15...
Cycle ('ABC') # repeated sequence elements, including a, B, c, a, B, c...
Repeat (1.2) # repeat 1.2 to form an infinite loop, that is, 1.2, 1.2 ,...

Repeat can also have a limit on the number of times:

Repeat (10, 5) # repeat 10, 5 times in total

Function tools

Function programming uses functions as the programming paradigm for processing objects. In Python, functions are also objects, so you can easily perform some functional processing, such as map (), filter (), reduce () functions.

Itertools contains similar tools. These functions receive functions as parameters and return the results as a iterator.

For example:

The code is 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, but returns a iterator instead of a sequence. Contains the results of elements 1, 4, 27, that is, 1 ** 1, 2 ** 2, 3 ** 3. The pow function (built-in multiplication function) is the first parameter. Pow () acts on each element of the next two lists in turn, and collects the function results to form the returned iterator.

You can also use the following functions:

The code is as follows:


Starmap (pow, [(1, 1), (2, 2), (3, 3)])


Pow will act on each tuple of the table in sequence.

The ifilter function is similar to the filter () function, but returns a iterator.

The code is as follows:


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


Lambda functions act on each element in sequence. if the function returns True, the original elements are collected. 6, 7

In addition,

The code is as follows:


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


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

The code is as follows:


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


When the function returns True, elements are collected to the iterator. Once the function returns False, it stops. 1, 3

The code is 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, all the remaining elements are collected to the iterator. 6, 7, 1.

Combined tools

We can combine the original iterator to obtain the new iterator.

The code is as follows:


Chain ([1, 2, 3], [4, 5, 7]) # connect two recyclers to become one. 1, 2, 3, 4, 5, 7
Product ('ABC', [1, 2]) # Cartesian product of multiple iterator sets. Equivalent to nested loop
For m, n in product ('ABC', [1, 2]):
Print m, n

Permutations ('ABC', 2) # select two elements from 'abcd', such as AB, bc,... sort all the results and return the new iterator.

Note that the preceding combination is ordered, that is, AB and ba are all returned.

Combinations ('ABC', 2) # select two elements from 'abcd', such as AB, bc,... sort all the results and return the new iterator.

Note: If the preceding combination is in no order, that is, AB and ba, only one AB is returned.

Combinations_with_replacement ('ABC', 2) # similar to the preceding one, but the selected elements can be repeated twice. Aa, bb, and cc are added.

Groupby ()

Apply the key function to each element of the original iterator. Based on the key function result, the elements with the same function result are assigned to a new iterator. Each new iterator uses the function return result as a tag.

This is like the height of a group of people as a loop. We can use this key function: if the height is greater than 180, "tall" is returned; if the height is at least 160, "short" is returned; "middle" is returned in the middle ". In the end, all the heights are divided into three recyclers: "tall", "short", and "middle ".

The code is 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,182,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 () to sort the elements of the original iterator according to the key function, so that the elements of the same group are first closer to each other.

Other tools

Compress ('abcd', [1, 1, 1, 0]) # Based on the true values of [1, 1, 1, 0, select the element in the first parameter 'ABC. A, B, C
Islice () # is similar to the slice () function, but returns a loop
Izip () # is similar to the zip () function, but returns a iterator.

Summary

Itertools tools can be implemented by yourself. Itertools only provides more forming solutions.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.