Python學習筆記__12.7章 itertools

來源:互聯網
上載者:User

標籤:程式設計語言   Python   

# 這是學習廖雪峰老師python教程的學習筆記

1、概覽

Python的內建模組itertools提供了非常有用的用於操作迭代對象的函數。

1.1、itertools提供的幾個“無限”迭代器

                0)count()

>>> import itertools

>>> natuals = itertools.count(1)

>>> for n in natuals:

...     print(n)

count()會建立一個無限的迭代器,所以上述代碼會列印出自然數序列,根本停不下來,只能按Ctrl+C退出。

                1)cycle()

cycle()會把傳入的一個序列無限重複下去

>>> import itertools

>>> cs = itertools.cycle('ABC') # 注意字串也是序列的一種

>>> for c in cs:

...     print(c)

                2)repeat()

repeat()負責把一個元素無限重複下去,不過如果提供第二個參數就可以限定重複次數

>>> ns = itertools.repeat('A', 3)

>>> for n in ns:

...     print(n)

                3)takewhile()

可以通過takewhile()等函數根據條件判斷來對無限迴圈截取出一個有限的序列

>>> natuals = itertools.count(1)

>>> ns = itertools.takewhile(lambda x: x <= 10, natuals)

>>> list(ns)

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

 

1.2、itertools提供的幾個迭代器操作函數

                1)chain()

chain()可以把一組迭代對象串聯起來,形成一個更大的迭代器

>>> for c in itertools.chain('ABC', 'XYZ'):

...     print(c)

# 迭代效果:'A' 'B' 'C' 'X' 'Y' 'Z'

                2)groupby()

groupby()把迭代器中相鄰的重複元素挑出來放在一起:

>>> for key, group in itertools.groupby('AAABBBCCAAA'):

...     print(key, list(group))

...

A ['A', 'A', 'A']

B ['B', 'B', 'B']

C ['C', 'C']

A ['A', 'A', 'A']

挑選規則是通過函數完成的,只要作用於函數的兩個元素返回的值相等,這兩個元素就被認為是在一組的,而函數傳回值作為組的key。

>>> for key, group in itertools.groupby('AaaBBbcCAAa', lambda c: c.upper()): # 忽略大小寫

...     print(key, list(group))

...

A ['A', 'a', 'a']

B ['B', 'B', 'b']

C ['c', 'C']

A ['A', 'A', 'a']

注意:itertools模組提供的全部是處理迭代功能的函數,它們的傳回值不是list,而是Iterator,只有用for迴圈迭代的時候才真正計算。

2、例題

計算圓周率可以根據公式:

利用Python提供的itertools模組,我們來計算這個序列的前N項和:

# -*- coding: utf-8 -*-

import itertools

方法一:

def pi(N): 

    n=itertools.count(1,2)  # 取出奇數序列,從1開始,步長為2

    ns=itertools.takewhile(lambda x:x<=2*N,n) #取出前N個數

    num=list(ns)  #將Iterator 序列化

    sum=0

    for n in num: # 迴圈,if判斷取值

        if n%4==1:

            n=4/n

        else:

            n=-4/n

        sum+=n

    return sum

方法二(網友寫):

def pi(N):

    ' 計算pi的值 '

    # step 1: 建立一個奇數序列: 1, 3, 5, 7, 9, ...

    list1 = itertools.count(1, 2)

    # step 2: 取該序列的前N項: 1, 3, 5, 7, 9, ..., 2*N-1.

    list2 = list(itertools.takewhile(lambda x: x < 2 * N, list1))

    # step 3: 添加正負符號並用4除: 4/1, -4/3, 4/5, -4/7, 4/9, ...

    list3 = [4 / (-i) for i in list2[1::2]] + [4 / i for i in list2[::2]]

    # step 4: 求和:

    return sum(list3) #這裡求和得用sum()函數,sum函數將list3中的所有值相加


Python學習筆記__12.7章 itertools

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.