Python itertools
include various iterators for efficient looping.
• count(begin [,step])
: from begin, begin+step, begin + 2 * step, ...
>>> from itertools import * >>> x = count(10) >>> for n in x: ... if (n==14): break ... print(n) ...
10 11 12 13•
cycle(iterable)
: iterates through the iterable over and over again
>>> from itertools import * >>> x = cycle('01') >>> j = 1; >>> for i in x: ... print(i,j) ... j += 1 ... if (j == 7): ... break ...
0 1 1 2 0 3 1 4 0 5 1 6•
repeat(i [,n])
: repeat i n times, if n is not specified, repeat i for ever
>>> from itertools import * >>> x = repeat(1, 5) >>> for i in x: print(i)
1 1 1 1 1•
chain(list1[],list2[], ...)
:
>>> from itertools import * >>> x = chain('12','654') >>> for i in x: >>> print(i)
1 2 6 5 4•
compress(data, selectors)
: Drop data based on selectors
>>> from itertools import * >>> x = compress([1,4,6,2,34,9],[True,False,True,True,True,False]) >>> for i in x: >>> print(i)
1 6 2 34•
dropwhile(...)
: Drop data based on condition
>>> from itertools import * >>> data = [1,4,6,2,34,9] >>> x = dropwhile(lambda x: x<10,data)#drop till the elements >=10 >>> for i in x: >>> print(i)
34 9•
takewhile(...)
: Save data based on condition
>>> from itertools import * >>> data = [1,4,6,2,34,9] >>> x = takewhile(lambda x: x<10,data)#drop after the elements >=10 >>> for i in x: >>> print(i)
1 4 6 2•
groupby(iterable[,keyfunc])
:
>>> from itertools import * >>> for i, j in groupby('55333--99'): >>> print (i,list(j))
5 ['5', '5'] 3 ['3', '3', '3'] - ['-', '-'] 9 ['9', '9']•
filter(contintion,data)
: filter data based on condition
>>> from itertools import * >>> data = [2,6,9,3,1,5] >>> x = filter(lambda x: x%2, data) >>> for i in x: print (i)
9 3 1 5•
filterfalse(contintion,data)
: filter data based on condition is FALSE
>>> from itertools import * >>> data = [2,6,9,3,1,5] >>> x = filterfalse(lambda x: x%2, data) >>> for i in x: print (i)
2 6•
islice(data,[start,]stop[,step])
: filter data from start to stop with step
>>> from itertools import * >>> data = [2,6,9,3,1,5,10,3,4,6,23] >>> x = islice(data,3,9,2) >>> for i in x: >>> print (i)
3 5 3