Python itertools operation iterables

The Python provides many built-in modules itertools iterative method of operating an object

Reference Links: https://www.liaoxuefeng.com/wiki/1016959663602400/1017783145987360

Unlimited iterator

  count()

  It returns an infinite iterator can be used to produce a natural number

Import the itertools >>> 
>>> natuals itertools.count = (. 1) may be bothered. 1 # omitted from zero by default 
>>> for n-in natuals: 
... Print (n-) 
... 
. 1 
2 
. 3 
... The cycle continues indefinitely unless terminated Ctrl + c

 

  cycle()

  Will the incoming sequence continues indefinitely

Import the itertools >>> 
>>> itertools.cycle CS = ( 'the ABC') # Note that the string is a sequence 
>>> for C in CS: 
... Print (C) 
... 
'A' 
'B ' 
' C ' 
' A ' 
' B ' 
' C ' 
...

 

  repeat()

  repeat()Responsible for an element continues indefinitely, but if the number of second parameter can define a repeating

 

  Only infinite sequence foriteration iteration will go on indefinitely, if only to create an iteration object, it does not advance to generate an infinite number of elements in it, in fact it is impossible to create an unlimited number of elements in memory. 

  Although infinitely infinite sequence of iterations to go, but we would usually through takewhile()other functions based on conditional to intercept a limited sequence:

>>> natuals = itertools.count(1)
>>> ns = itertools.takewhile(lambda x: x <= 10, natuals)
>>> list(ns)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

  

Several iterations operation function

  chain()

  chain()The objects may be a set of iterations together, forming a larger iterator:

>>> for c in itertools.chain('ABC', 'XYZ'):
...     print(c)
# 迭代效果:'A' 'B' 'C' 'X' 'Y' 'Z'

  

groupby()

  groupby()The iterator adjacent repeating elements singled out together:

>>> for key,group in itertools.groupby('AAAAABBBCCWW'):
...     print(key,list(group))#注意这里的list()
...
A ['A', 'A', 'A', 'A', 'A']
B ['B', 'B', 'B']
C ['C', 'C']
W ['W', 'W']

  Selection rule is actually done by a function, as long as the value is used for the two elements is equal to the function's return, these two elements are considered to be in a group, and the function returns the value set as the key. If we were to ignore the case group, we can let the elements 'A'and 'a'return the same key:

>>> for key, group in itertools.groupby('AaaBBbcCAAa', lambda c: c.upper()):
...     print(key, list(group))
...
A ['A', 'a', 'a']
B ['B', 'B', 'b']
C ['c', 'C']
A ['A', 'A', 'a']

  

Guess you like

Origin www.cnblogs.com/Gaoqiking/p/11616268.html