Python学习笔记—itertools模块

这篇是看wklken的《Python进阶-Itertools模块小结》 学习itertools模块的学习笔记

在看itertools中各函数的源代码时,刚开始还比较轻松,但后面看起来就比较费劲。。。

1、itertools.count(start=0,step=1)

    此函数用来创建一个迭代器,生成从n开始的连续整数,如果忽略n,则从0开始计算

  如果超出了sys.maxint,计数器将溢出并继续行-sys.maxint-1开始计算

  定义:

def count(start=0, step=1):
    #count(10) --> 10, 11, 12, 13.....
    # count(2.5, 0.5)--> 2.5, 3.0, 3.5 ....
    n = start
    while True:
        yield n
        n += step

  使用:

from itertools import *

for i in izip(count(i), ['a', 'b', 'c']):
    print i

out:
(1, 'a')
(2, 'b')
(3, 'c')

2、itertools.cycle(iterable)

  创建一个迭代器,对iterable中的元素反复执行循环操作,内部会生成iterable中的元素的一个副本, 次副本用于返回循环中的重复项

  定义:

def cycle(iterable):
    # cycle('ABCD') --> 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

  使用:

from itertools import *

i = 0
for item in cycle(['a', 'b', 'c']):
    i += 1
    if i == 6:
        break
    print (i, item)

out:
(1, 'a')
(2, 'b')
(3, 'c')
(4, 'a')
(5, 'b')

3、itertools.repeat(object[, times])

  创建一个迭代器,重复生成object, times (如果已提供) 指定重复计数, 如果未提供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(time):
            yield object

  使用:

from itertools import *

for i in repeat('over-and-over', 3):
    print i

out:
over-and-over
over-and-over
over-and-over

4、itertools.chain(*iterables)

  将多个迭代器作为参数,但只返回单个迭代器,它产生所有参数迭代器的内容,就好像他们来自于一个单一的序列。

  定义:

def chain(*iterables):
    # chain('ABC', 'DEF') --> A B C D E F
    for it in iterables:
        for element in it:
            yield element

  使用:

from itertools import *

for i in chain([1, 2, 3], ['a', 'b', 'c']):
    print i

out:
1
2
3
a
b
c

5、itertools.compress(data, selectors)

提供一个选择列表, 对原始数据进行筛选

定义:

def compress(data, selectors):
    # compress('ABCDEF', [1, 0, 1, 0, 1, 1]) --> A C E F
    return (d for d, s in izip(data, selectors) if s)

 6、itertools.product(*iterables[, repeat])

笛卡尔积

创建一个迭代器,生成item1, item2等中的项目的笛卡尔积的元组, repeat是一个关键字参数,指定重复生成序列的次数。

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)
import itertools
a = (1, 2, 3)
b = ('a', 'b', 'c')
c = itertools.product(a, b)
for elem in c:
    print elem

out:
(1, 'A')
(2, 'B')
(3, 'C')
(2, 'A')
(2, 'B')
(2, 'C')
(3, 'A')
(3, 'B')
(3, 'C')

这个模块函数有好多,有好多敲了一遍忘了保存,懒得再敲了,但也记得差不多了,所以就这样吧

posted @ 2015-07-11 15:28  第八片叶子  阅读(288)  评论(0编辑  收藏  举报