python itertools常用方法总结

1.count

itertools.count函数返回的生成器能生成多个数,如果不传入参数,itertools.count函数会生成从零开始的整数数列。不过,我们可以提供可选的start和step值。

import itertools
gen = itertools.count(1, .5)
next(gen)   #1
next(gen)   # 1.5
next(gen)   # 2.0
.
.
.

然后itertools.count 从不停止。如果调用list(count())就会报内存泄露的错误。不过.itertools.takewhile函数则不同,他会生成一个使用另一个生成器的生成器。在指定的条件计算结果为False时停止。因此,可以把这两个函数结合在一起使用。

gen = itertools.takewhile(lambda n: n<3, itertools.count(1, .5))
list(gen)    #[1, 1.5, 2.0, 2.5]
>>> def vowel(c):
... return c.lower() in 'aeiou'
...
>>> list(filter(vowel, 'Aardvark'))
['A', 'a', 'a']
>>> import itertools
>>> list(itertools.filterfalse(vowel, 'Aardvark'))
['r', 'd', 'v', 'r', 'k']
>>> list(itertools.dropwhile(vowel, 'Aardvark'))
['r', 'd', 'v', 'a', 'r', 'k']
>>> list(itertools.takewhile(vowel, 'Aardvark'))
['A', 'a']
>>> list(itertools.compress('Aardvark', (1,0,1,1,0,1)))
['A', 'r', 'd', 'a']
>>> list(itertools.islice('Aardvark', 4))
['A', 'a', 'r', 'd']
>>> list(itertools.islice('Aardvark', 4, 7))
['v', 'a', 'r']
>>> list(itertools.islice('Aardvark', 1, 7, 2))
['a', 'd', 'a']
>>> sample = [5, 4, 2, 8, 7, 6, 3, 0, 9, 1]
>>> import itertools
>>> list(itertools.accumulate(sample)) 
[5, 9, 11, 19, 26, 32, 35, 35, 44, 45]
>>> list(itertools.accumulate(sample, min))
[5, 4, 2, 2, 2, 2, 2, 0, 0, 0]
>>> list(itertools.accumulate(sample, max))
[5, 5, 5, 8, 8, 8, 8, 8, 9, 9]
>>> import operator
>>> list(itertools.accumulate(sample, operator.mul))
[5, 20, 40, 320, 2240, 13440, 40320, 0, 0, 0]
>>> list(itertools.accumulate(range(1, 11), operator.mul))
[1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]

2. chain(*iterables)

创建一个迭代器,该迭代器从第一个迭代中返回元素,直到耗尽,然后继续进行下一个迭代,直到所有的迭代器都被耗尽.用于将连续序列作为单个序列进行处理,大致相当于:

def chain(*iterables):
    # chain('ABC', 'DEF') --> A B C D E F
    for it in iterables:
        for element in it:
            yield element
python itertools常用方法总结_第1张图片
chain method.png

3.cycle(iterable)

让迭代器从迭代中返回元素,并保存每个元素的副本.当迭代耗尽时,从保存的副本返回元素.重复下去.大致相当于:

def cycle(iterable):
    # cycle('ABCD') --> A B C D A B C D A B C D ...
    saved = []
    for element in iterable:
        yield element
        saved.append(element)
    while saved:
        for element in saved:
              yield element
cycle method.png

你可能感兴趣的:(python itertools常用方法总结)