1. 程式人生 > >Python學習筆記(四) 列表生成式_生成器

Python學習筆記(四) 列表生成式_生成器

rec triangle 小寫 ont 無限 end clas 普通 執行過程

筆記摘抄來自:https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014317799226173f45ce40636141b6abc8424e12b5fb27000

本文章僅供自己復習使用,侵刪;

  • 列表生成器
# 例如,列出當前目錄下的所有文件和目錄名,可以通過一行代碼實現:
import os
[d for d in os.listdir(.)]
#for循環後面還可以加上if判斷,這樣我們就可以篩選出僅偶數的平方: [4, 16, 36, 64, 100]
 [x * x for
x in range(1, 11) if x % 2 ==
0]

#最後把一個list中所有的字符串變成小寫:

L = [Hello, World, IBM, Apple]
[s.lower() for s in L]   # [‘hello‘, ‘world‘, ‘ibm‘, ‘apple‘]

  • 生成器

通過列表生成式,我們可以直接創建一個列表。但是,受到內存限制,列表容量肯定是有限的。而且,創建一個包含100萬個元素的列表,不僅占用很大的存儲空間,如果我們僅僅需要訪問前面幾個元素,那後面絕大多數元素占用的空間都白白浪費了。

所以,如果列表元素可以按照某種算法推算出來,那我們是否可以在循環的過程中不斷推算出後續的元素

呢?這樣就不必創建完整的list,從而節省大量的空間。在Python中,這種一邊循環一邊計算的機制,稱為生成器:generator

要創建一個generator,有很多種方法。第一種方法很簡單,只要把一個列表生成式的[]改成(),就創建了一個generator:

我們可以直接打印出list的每一個元素,但我們怎麽打印出generator的每一個元素呢?

如果要一個一個打印出來,可以通過 next() 函數獲得generator的下一個返回值:

>>> next(g)
0
>>> next(g)
1
>>> next(g)
4 >>> next(g) 9 >>> next(g) 16 >>> next(g) 25 >>> next(g) 36 >>> next(g) 49 >>> next(g) 64 >>> next(g) 81 >>> next(g) Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration

正確的方法是使用for循環,因為generator也是可叠代對象:

>>> g = (x * x for x in range(10))
>>> for n in g:
...     print(n)
... 
0
1
4
9
16
25
36
49
64
81

如果推算的算法比較復雜,用類似列表生成式的for循環無法實現的時候,還可以用函數來實現。

比如,著名的斐波拉契數列(Fibonacci),除第一個和第二個數外,任意一個數都可由前兩個數相加得到:

1, 1, 2, 3, 5, 8, 13, 21, 34, ...

def fib(max):
    n, a, b = 0, 0, 1
    while n < max:
        yield b              #如果一個函數定義中包含yield關鍵字,那麽這個函數就不再是一個普通函數,而是一個generator:
        a, b = b, a + b
        n = n + 1
    return done

這裏,最難理解的就是generator和函數的執行流程不一樣。函數是順序執行,遇到return語句或者最後一行函數語句就返回。而變成generator的函數在每次調用next()的時候執行,遇到yield語句返回,再次執行時 從上次返回的yield語句處繼續執行。

舉個簡單的例子,定義一個generator,依次返回數字1,3,5:

def odd():
    print(step 1)
    yield 1
    print(step 2)
    yield(3)
    print(step 3)
    yield(5)

調用該generator時,首先要生成一個generator對象,然後用next()函數不斷獲得下一個返回值:

>>> o = odd()
>>> next(o)
step 1
1
>>> next(o)
step 2
3
>>> next(o)
step 3
5
>>> next(o)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

可以看到,odd不是普通函數,而是generator,在執行過程中,遇到yield就中斷,下次又繼續執行。執行3次yield後,已經沒有yield可以執行了,所以,第4次調用next(o)就報錯。

回到fib的例子,我們在循環過程中不斷調用yield,就會不斷中斷。當然要給循環設置一個條件來退出循環,不然就會產生一個無限數列出來。

同樣的,把函數改成generator後,我們基本上從來不會用next()來獲取下一個返回值,而是直接使用for循環來叠代:

>>> for n in fib(6):
...     print(n)
...
1
1
2
3
5
8

但是用for循環調用generator時,發現拿不到generator的return語句的返回值。如果想要拿到返回值,必須捕獲StopIteration錯誤,返回值包含在StopIterationvalue中:

>>> g = fib(6)
>>> while True:
...     try:
...         x = next(g)
...         print(g:, x)
...     except StopIteration as e:
...         print(Generator return value:, e.value)
...         break
...
g: 1
g: 1
g: 2
g: 3
g: 5
g: 8
Generator return value: done

  • 楊輝三角
def triangles():
    l=[1]
    r=[]
    while True:
        l=r
        r=[]
        for i in list(range(1,len(l)+2)):
            if (i-1)<=0 or i>len(l):
                r.append(1)
            else:
                r.append(l[i-2]+l[i-1])
        yield r      #每次執行從這裏退出,下次執行時,從這裏開始
     
n = 0
for t in triangles():
    print(t)
    n = n + 1
    if n == 10:
        break

Python學習筆記(四) 列表生成式_生成器