Python 列表推導式與生成器
推導式
會直接生成一個相應的對象,也叫解析式
列表推導式
list_i = [i for i in range(0,25)]
print(list_i)
print(type(list_i))
#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
#<class 'list'>
可以很明顯的看出列表推導式就是快速的生成了一個列表
當然,可以增加篩選條件
list_i = [i for i in range(0,25) if i % 2 != 0]#篩選出0到24的所有奇數
print(list_i)#[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23]
其他的推導式也相同
字典推導式
x = ['a','b','c']
y = [1,2,3]
dict_i = {k: v for k,v in zip(x,y)}
print(dict_i) #{'a': 1, 'b': 2, 'c': 3}
#增加篩選條件,鍵不為a并且值大于2
dict_i = {k: v for k,v in zip(x,y) if k != 'a'and v > 2}
print(dict_i) #{'c': 3}
集合推導式
set_i = {i*i for i in [1,1,2,2,4,5,7]}
print(set_i)#{1, 4, 16, 49, 25} 已去重
print(type(set_i))#<class 'set'>
優缺點
推導式可以快速的生成列表、字典和集合,方便快捷。
但是會一次性占用很大空間
生成器
解決推導式空間占有的方法就是生成器了,生成器不會一次性的占有一塊存儲空間,而是通過yield的方式一個一個的生成。除此之外生成器還有保存狀態的特性。
調用了yield的函數叫做生成器函數,它返回一個迭代器。
使用案例
def fibonacci(num):#斐波那契數列生成器
a,b,counter = 0,1,0
while True:
if (counter > num):
return
yield a
a,b = b, a+b
counter += 1
f = fibonacci(10)
print(f)#<generator object fibonacci at 0x10759fa40> #返回一個生成器對象
print(next(f))
print(next(f))
print(next(f))
print(next(f))
'''
#和迭代器一樣,通過next的方式輸出下一個元素
0
1
1
2
3
'''
保存狀態與StopIteration
注意,接著以上代碼,加上
while True:
print(next(f))
得到的結果是
'''
5
8
13
21
34
55
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
~/wencyyyyyy/iterator_and_generator.py in
1 while True:
----> 2 print(next(f))
StopIteration:
'''
這里并非從斐波那契數列的0開始,而是接著上面已經輸出過的3,接著往下5、8、13、21、34、55
是因為在調用生成器運行的過程中,每次遇到 yield 時函數會暫停并保存當前所有的運行信息,返回 yield 的值, 并在下一次執行 next() 方法時從當前位置繼續運行,這就是生成器的==保存狀態==。
保存狀態
這里在原代碼中加入一行標志
def fibonacci(num):
a,b,counter = 0,1,0
while True:
if (counter > num):
return
yield a
print('這是第{}次'.format(counter))
a,b = b, a+b
counter += 1
f = fibonacci(10)
print(f)
print(next(f))
'''
<generator object fibonacci at 0x1076e7830>
0
'''
這里并沒有輸出,這是第counter次。說明函數確實執行到yield就暫停了。那么下次next(f)時有沒有繼續從上次結束的地方運行呢?
print(next(f))
'''
這是第0次
1
'''
很明顯,確實是從上次結束的的地方繼續運行的。
StopIteration
此外,出現了一個異常,StopIteration 。這里沒什么好解釋的,因為生成器返回的是一個迭代器。迭代完成,斐波那契數列中數字超過10個時,就代表迭代已經完成。
聯系方式
如果您對本片博文有任何意見或者建議,歡迎您聯系我