Python Tutorial

Saturday, May 4, 2013

Itertools - Python iterators terminating on the shortest input sequence.

Iterators terminating on the shortest input sequence:
  • imap : Make an iterator that computes the function using arguments from each of the iterables. Always consider shortest iterables.
  • chain : Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable ans so on.
  • ifilter : Make an iterator that filters elements from iterable returning only those for which the predicate is True.
  • ifilterfalse : Make an iterator that filters elements from iterable returning only those for which the predicate is False.
  • compress : Make an iterator that filters elements from data returning only those that have a corresponding element in selectors that evaluates to True.
  • izip : Make an iterator that aggregates elements from each of the iterables.
  • izip_longest : Same as izip, except for uneven length values are filled by default None.
import itertools

def add(*args):
  s = 0;
  for num in args:
    s += num
  return s

print "imap example:"
# will calculate 5+2+10, 2+3+10
for n in itertools.imap(add, (5,2,3), (2, 3, 3),(10, 10)):
    print n


print "chain example"
for ch in itertools.chain('ABC','DEF'):
  print ch


print "ifilter example "
A = [1,2,4,5,7,8]
for n in itertools.ifilter(lambda x:x%2 ,A):
  print n


print "ifilterfalse example:"
for n in itertools.ifilterfalse(lambda x:x%2 ,A):
  print n


print "compress example:"
for ch in itertools.compress('abcdef',[0,1,0,1,1,1]):
  print ch

Output:
imap example:
17
15
chain example
A
B
C
D
E
F
ifilter example 
1
5
7
ifilterfalse example:
2
4
8
compress example:
b
d
e
f
izip example:
('a', 'X')
('b', 'Y')
izip_longest example:
('a', 'X')
('b', 'Y')
('c', None)
('d', None)

0 comments:

Post a Comment