Introduction to the Python standard library circulator (itertools)

Source: Internet
Author: User
Tags imap pow sorts
In the Loop object and function object, we understand the function of the circulator (iterator). A circulator is a container for objects that contain multiple objects. By invoking the next () method of the Circulator (__next__ () method, in Python 3.x), the Circulator returns an object in turn. Until all the objects are traversed, the circulator will cite the stopiteration error.

In the for-I in iterator structure, each time the loop returns an object, it is assigned to I until the loop ends. Using the ITER () built-in function, we can turn containers such as tables, dictionaries, and so on into circulators. Like what:

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 for generating the circulator. Most of the input to these tools is the existing circulator. On the other hand, these tools are completely self-fulfilling with Python, which simply provides a relatively standard and efficient way to implement them. This is also in line with Python's "only and best solution only" concept.

The code is as follows:


# Import the Tools
From itertools Import *

Infinite loop device

Count (5, 2) #从5开始的整数循环器, increase by 2, 5, 7, 9, 11, 13, 15, each time ...
Cycle (' abc ') #重复序列的元素, both A, B, C, a, B, c ...
Repeat (1.2) #重复1.2, constituting an infinite circulator, i.e. 1.2, 1.2, 1.2, ...

Repeat can also have a frequency limit:

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 do some functional processing, such as map (), filter (), and reduce () functions.

The itertools contains similar tools. These functions receive functions as parameters and return the result as a circulator.

Like what:

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, except that it returns a loop instead of a sequence. Contains the result of element 1, 4, 27, which is 1**1, 2**2, 3**3. Function Pow (built-in exponentiation function) as the first parameter. The POW () acts on each element of the next two lists in turn, and collects the result of the function, forming the returned circulator.

In addition, you can also use the following function:

The code is as follows:


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


The 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 circulator.

The code is as follows:


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


The lambda function acts on each element in turn, and if the function returns True, the original element is 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 collects elements that return false. 2, 3, 5

The code is as follows:


TakeWhile (Lambda x:x < 5, [1, 3, 6, 7, 1])


When the function returns True, the element is collected to the circulator. 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, it starts collecting all the remaining elements into the circulator. 6, 7, 1.

Combo Tool

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

The code is as follows:


Chain ([1, 2, 3], [4, 5, 7]) # Connect two circulators to become one. 1, 2, 3, 4, 5, 7
Product (' abc ', [1, 2]) # The Cartesian product of multiple circulator sets. 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, ... Sorts all the results back to the new circulator.

Note that the above combinations are sorted in order, i.e. AB, BA are returned.

Combinations (' abc ', 2) # pick two elements from ' ABCD ', such as AB, BC, ... Sorts all the results back to the new circulator.

Note that the above combinations are not sorted in order, i.e. AB, ba words, only return an AB.

Combinations_with_replacement (' abc ', 2) # is similar to above but allows two selected elements to repeat. That's a lot more AA, BB, CC.

GroupBy ()

The key function is applied to each element of the original circulator. Based on the result of the key function, the elements that have the same function result are divided into a new circulator. Each new circulator returns the result as a label for the function.

It's like a group of people's height as a circulator. We can use such a key function: If the height is greater than 180, return "tall", if the height is 160, return "short", the Middle return "middle". Eventually, all the height will be divided into three circulator, namely "tall", "short", "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,, 177, 181, 182,] 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 circulator, sort by the key function, and let the same group of elements move closer to the position first.

Other tools

Compress (' ABCD ', [1, 1, 1, 0]) # Select the element in the first parameter ' ABCD ' according to the true and false values of [1, 1, 1, 0]. A, B, C
Islice () # is similar to the slice () function, just returns a Circulator
Izip () # is similar to the zip () function, but only returns a circulator.

Summarize

Itertools tools can be implemented on their own. Itertools just provides a more formed solution.

  • 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.