This chapter will introduce the Python self itertools
-built module, for more information, refer to: Python reference guide
Python's self-built modules itertools
provide useful functions for manipulating iterative objects.
First, let's look at itertools
the several 无限
iterators provided:
>>>import itertools>>>= itertools.count(1)>>>forin natuals: print(n)123...
Because count()
an infinite iterator is created, the above code prints out a sequence of natural numbers that cannot be stopped and can only be Ctrl+C
exited.
cycle()
Repeats the incoming sequence indefinitely:
>>>import itertools>>>= itertools.cycle('ABC')>>>forin cs: print(c)'A''B''C''A''B''C'
repeat()
It is the responsibility to repeat an element indefinitely, but if you provide a second argument you can limit the number of repetitions:
>>>= itertools.repeat('A'3)>>>forin ns: print(n)AAA
An infinite sequence is iterated indefinitely only at for
iteration, and if only an iterative object is created, it does not generate an infinite number of elements beforehand, and in fact it is not possible to create an infinite number of elements in memory.
>>>= itertools.count(1)>>>= itertools.takewhile(lambda<=10, natuals)>>>list(ns)[12345678910]
itertools
Several iterator manipulation functions are provided that are more useful:
Chain ()
chain()
You can concatenate a set of iterative objects together to form a larger iterator:
>>>forin itertools.chain('ABC''XYZ'): print(c)#迭代效果:'A', 'B', 'C', 'X', 'Y', 'Z'
GroupBy ()
groupby()
Pick out the repeating elements that are adjacent to the iterator
>>>forin itertools.groupby('AAABBBCCAAA')>>> printlist(group))A ['A''A''A']B ['B''B''B']C ['C''C']A ['A''A''A']
In fact, when the rule is selected through the function, as long as the function is equal to the value returned by the two elements, the element is considered to be together, and the function returns the value as the key of the group. If we want to ignore the case grouping, we can let A
the element and a
both return the same key:
>>>forin itertools.groupby('AaaBBbcCAAa'lambda c: c.super()): printlist(group))A ['A''a''a']B ['B''B''b']C ['c''C']A ['A''A''a']
Summary
itertools
The module provides all the functions that deal with the iteration function, and their return value is not list
, but Iterator
only for
when the loop iteration is used to really calculate.
Python's Itertools module