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學起。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章