# Python中itertools模块用法详解

chain(iter1, iter2, ..., iterN):

```
from itertools import chain
test = chain('AB', 'CDE', 'F')
for el in test:
print el

A
B
C
D
E
F

```

chain.from_iterable(iterables):

```
>>> def f(iterables):
for x in iterables:
for y in x:
yield y

>>> test = f('ABCDEF')
>>> test.next()
'A'

>>> from itertools import chain
>>> test = chain.from_iterable('ABCDEF')
>>> test.next()
'A'

```

combinations(iterable, r):

```
>>> from itertools import combinations
>>> test = combinations([1,2,3,4], 2)
>>> for el in test:
print el

(1, 2)
(1, 3)
(1, 4)
(2, 3)
(2, 4)
(3, 4)

```

count([n]):

cycle(iterable):

dropwhile(predicate, iterable):

```
def dropwhile(predicate, iterable):
# dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1
iterable = iter(iterable)
for x in iterable:
if not predicate(x):
yield x
break
for x in iterable:
yield x

```

groupby(iterable [,key]):

ifilter(predicate, iterable):

```
ifilter(lambda x: x%2, range(10)) --> 1 3 5 7 9

```

ifilterfalse(predicate, iterable):

```
ifilterfalse(lambda x: x%2, range(10)) --> 0 2 4 6 8

```

imap(function, iter1, iter2, iter3, ..., iterN)

```
>>> from itertools import *
>>> d = imap(pow, (2,3,10), (5,2,3))
>>> for i in d: print i

32
9
1000

####
>>> d = imap(pow, (2,3,10), (5,2))
>>> for i in d: print i

32
9

####
>>> d = imap(None, (2,3,10), (5,2))
>>> for i in d : print i

(2, 5)
(3, 2)

```

islice(iterable, [start, ] stop [, step]):

```
def islice(iterable, *args):
# islice('ABCDEFG', 2) --> A B
# islice('ABCDEFG', 2, 4) --> C D
# islice('ABCDEFG', 2, None) --> C D E F G
# islice('ABCDEFG', 0, None, 2) --> A C E G
s = slice(*args)
it = iter(xrange(s.start or 0, s.stop or sys.maxint, s.step or 1))
nexti = next(it)
for i, element in enumerate(iterable):
if i == nexti:
yield element
nexti = next(it)

#If start is None, then iteration starts at zero. If step is None, then the step defaults to one.
#Changed in version 2.5: accept None values for default start and step.

```

izip(iter1, iter2, ... iterN):

```
def izip(*iterables):
# izip('ABCD', 'xy') --> Ax By
iterables = map(iter, iterables)
while iterables:
yield tuple(map(next, iterables))

```

izip_longest(iter1, iter2, ... iterN, [fillvalue=None]):

```
def izip_longest(*args, **kwds):
# izip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-
fillvalue = kwds.get('fillvalue')
def sentinel(counter = ([fillvalue]*(len(args)-1)).pop):
yield counter()     # yields the fillvalue, or raises IndexError
fillers = repeat(fillvalue)
iters = [chain(it, sentinel(), fillers) for it in args]
try:
for tup in izip(*iters):
yield tup
except IndexError:
pass

```

permutations(iterable [,r]):

```
def permutations(iterable, r=None):
# permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
# permutations(range(3)) --> 012 021 102 120 201 210
pool = tuple(iterable)
n = len(pool)
r = n if r is None else r
if r > n:
return
indices = range(n)
cycles = range(n, n-r, -1)
yield tuple(pool[i] for i in indices[:r])
while n:
for i in reversed(range(r)):
cycles[i] -= 1
if cycles[i] == 0:
indices[i:] = indices[i+1:] + indices[i:i+1]
cycles[i] = n - i
else:
j = cycles[i]
indices[i], indices[-j] = indices[-j], indices[i]
yield tuple(pool[i] for i in indices[:r])
break
else:
return

```

product(iter1, iter2, ... iterN, [repeat=1]):

```
def product(*args, **kwds):
# product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
# product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
pools = map(tuple, args) * kwds.get('repeat', 1)
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
for prod in result:
yield tuple(prod)

```

repeat(object [,times]):

```
def repeat(object, times=None):
# repeat(10, 3) --> 10 10 10
if times is None:
while True:
yield object
else:
for i in xrange(times):
yield object

```

starmap(func [, iterable]):

```
def starmap(function, iterable):
# starmap(pow, [(2,5), (3,2), (10,3)]) --> 32 9 1000
for args in iterable:
yield function(*args)

```

takewhile(predicate [, iterable]):

```
def takewhile(predicate, iterable):
# takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4
for x in iterable:
if predicate(x):
yield x
else:
break

```

tee(iterable [, n]):

```
def tee(iterable, n=2):
it = iter(iterable)
deques = [collections.deque() for i in range(n)]
def gen(mydeque):
while True:
if not mydeque:       # when the local deque is empty
newval = next(it)    # fetch a new value and
for d in deques:    # load it to all the deques
d.append(newval)
yield mydeque.popleft()
return tuple(gen(d) for d in deques)

#Once tee() has made a split, the original iterable should not be used anywhere else; otherwise,
the iterable could get advanced without the tee objects being informed.
#This itertool may require significant auxiliary storage (depending on how much temporary data needs to be stored).
In general, if one iterator uses most or all of the data before another iterator starts, it is faster to use list() instead of tee().

```

QQ号联系： 360901061

【本文对您有帮助就好】