Python学习笔记(十六)内建模块之Itertools

参考资料:https://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001415616001996f6b32d80b6454caca3d33c965a07611f000

Python的内建模块itertools提供了非常有用的用于操作迭代对象的函数。

1、count(n, m):从指定数字n开始按给定步长m无限迭代生成数字序列。

2、cycle(序列):通过无限迭代的方式生成由给定序列的元素组成的序列。

3、repeat(元素, 次数):将指定元素重复给定次数。

4、takewhile(函数, 迭代函数):通过函数指定迭代函数的终止条件,形成新的迭代函数。

5、chain(迭代函数/序列1,迭代函数/序列2):将两个序列或迭代函数序列串联组成更大的迭代器。

6、groupby(迭代函数/序列):把迭代器中相邻的重复元素挑选出来放在一起。

7、imap(函数,迭代函数/序列1,迭代函数/序列2):将给定函数作用于给定的两个序列或迭代函数序列生成新的序列,结果序列长度以短的为准。是map函数的迭代(惰性)实现。

8、ifilter(函数,迭代函数/序列):通过给定函数作用于序列或迭代函数序列元素的结果对源序列进行过滤。是filter函数的迭代(惰性)实现。

下面是我的学习代码:

import itertools

#调用itertools.count按step步长输出n次迭代结果
def Counter(n, step):
    nn = itertools.count(1, step)
    i = 1
    for m in nn:
        print m
        i = i + 1
        if i > n:
            break

def Cycler(n, s):
    nn = itertools.cycle(s)
    i = 1
    for m in nn:
        print m
        i = i + 1
        if i > n:
            break

def Repeater(n, s):
    nn = itertools.repeat(s, n)
    for m in nn:
        print m

def Takewhile(max, step):
    nn = itertools.count(step)
    ns = itertools.takewhile(lambda x: x <= max, nn)
    for m in ns:
        print m
        
def Test():
    print "call itertools.count to print Numbers setpped with 2 and iterred 10 times:"
    Counter(10, 2)
    print "call itertools.cycle to print repeat ABC with 10 times:"
    Cycler(10, 'ABC')
    print "call itertools.repeat to print repeat ABC with 10 times:"
    Repeater(10, 'ABC')
    print "call itertools.takewhile and itertools.count to print Numbers started from 2 and limited maxvalue as 10:"
    Takewhile(10, 2)
    print "call itertools.chain:"
    n1 = itertools.takewhile(lambda x: x < 10, itertools.count(1))
    n2 = itertools.takewhile(lambda x: x < 10, itertools.count(0.5, 0.5))
    n = itertools.chain(n1, n2)
    for m in n:
        print m
    print "call itertools.groupby:"
    for key, group in itertools.groupby("AAABBCCCAA"):
        print key, list(group)
    print "call itertools.imap:"
    #将后两个元素集按照给定的函数作运算
    for m in itertools.imap(lambda x, y : x * y, [10, 20, 30], [1, 2, 3]):
        print m
    print "call map:"
    r = itertools.takewhile(lambda x : x < 10, itertools.count(1))
    m = map(lambda x : x * x, r)
    print m
    print "call ifilter:"
    r = itertools.takewhile(lambda x : x < 10, itertools.count(1))
    for m in itertools.ifilter(lambda x : x < 10, r):
        print m
今天就学习到这里,下一节从XML学起。

猜你喜欢

转载自blog.csdn.net/alvin_2005/article/details/80504897