Python進階:生成器 懶人版本的迭代器詳解
從容器、可迭代對象談起
所有的容器都是可迭代的(iterable),迭代器提供了一個next方法。iter()返回一個迭代器,通過next()函數(shù)可以實現(xiàn)遍歷。
def is_iterable(param):
try:
iter(param)
return True
except TypeError:
return False
params = [
1234,
'1234',
[1, 2, 3, 4],
set([1, 2, 3, 4]),
{1:1, 2:2, 3:3, 4:4},
(1, 2, 3, 4)
]
for param in params:
print('{} is iterable? {}'.format(param, is_iterable(param)))
########## 輸出 ##########
# 1234 is iterable? False
# 1234 is iterable? True
# [1, 2, 3, 4] is iterable? True
# {1, 2, 3, 4} is iterable? True
# {1: 1, 2: 2, 3: 3, 4: 4} is iterable? True
# (1, 2, 3, 4) is iterable? True
除了數(shù)字外,其他數(shù)據(jù)結(jié)構(gòu)都是可迭代的。
生成器是什么
生成器是懶人版本的迭代器。例:
import os
import psutil
#顯示當(dāng)前 python 程序占用的內(nèi)存大小
def show_memory_info(hint):
pid = os.getpid()
p = psutil.Process(pid)
info = p.memory_full_info()
memory = info.uss / 1024. / 1024
print('{} memory used: {} MB'.format(hint, memory))
def test_iterator():
show_memory_info('initing iterator')
list_1 = [i for i in range(100000000)]
show_memory_info('after iterator initiated')
print(sum(list_1))
show_memory_info('after sum called')
def test_generator():
show_memory_info('initing generator')
list_2 = (i for i in range(100000000))
show_memory_info('after generator initiated')
print(sum(list_2))
show_memory_info('after sum called')
test_iterator()
test_generator()
%time test_iterator()
%time test_generator()
######### 輸出 ##########
initing iterator memory used: 48.9765625 MB
after iterator initiated memory used: 3920.30078125 MB
4999999950000000
after sum called memory used: 3920.3046875 MB
Wall time: 17 s
initing generator memory used: 50.359375 MB
after generator initiated memory used: 50.359375 MB
4999999950000000
after sum called memory used: 50.109375 MB
Wall time: 12.5 s
[i for i in range(100000000)] 聲明了一個迭代器,每個元素在生成后都會保存到內(nèi)存中,占用了巨量的內(nèi)存。(i for i in range(100000000)) 初始化了一個生成器,可以看到,生成器并不會像迭代器一樣占用大量的內(nèi)存,相比于 test_iterator(),test_generator()函數(shù)節(jié)省了一次生成一億個元素的過程。在調(diào)用next()的時候,才會生成下一個變量.
生成器能玩啥花樣
數(shù)學(xué)中有一個恒等式,(1 + 2 + 3 + ... + n)^2 = 1^3 + 2^3 + 3^3 + ... + n^3,用以下代碼表達
def generator(k):
i = 1
while True:
yield i ** k
i += 1
gen_1 = generator(1)
gen_3 = generator(3)
print(gen_1)
print(gen_3)
def get_sum(n):
sum_1, sum_3 = 0, 0
for i in range(n):
next_1 = next(gen_1)
next_3 = next(gen_3)
print('next_1 = {}, next_3 = {}'.format(next_1, next_3))
sum_1 += next_1
sum_3 += next_3
print(sum_1 * sum_1, sum_3)
get_sum(8)
########## 輸出 ##########
# <generator object generator at 0x000001E70651C4F8>
# <generator object generator at 0x000001E70651C390>
# next_1 = 1, next_3 = 1
# next_1 = 2, next_3 = 8
# next_1 = 3, next_3 = 27
# next_1 = 4, next_3 = 64
# next_1 = 5, next_3 = 125
# next_1 = 6, next_3 = 216
# next_1 = 7, next_3 = 343
# next_1 = 8, next_3 = 512
# 1296 1296
generator()這個函數(shù),它返回了一個生成器,當(dāng)運行到y(tǒng)ield i ** k時,暫停并把i ** k作為next()的返回值。每次調(diào)用next(gen)時,暫停的程序會啟動并往下執(zhí)行,而且i的值也會被記住,繼續(xù)累加,最后next_1為8,next_3為512.
仔細查看這個示例,發(fā)現(xiàn)迭代器是一個有限集合,生成器則可以成為一個無限集。調(diào)用next(),生成器根據(jù)運算會自動生成新的元素,然后返回給你,非常便捷。
再來看一個問題:給定一個list和一個指定數(shù)字,求這個數(shù)字在list中的位置:
#常規(guī)寫法 def index_normal(L, target): result = [] for i, num in enumerate(L): if num == target: result.append(i) return result print(index_normal([1, 6, 2, 4, 5, 2, 8, 6, 3, 2], 2)) ########## 輸出 ########## [2, 5, 9] #生成器寫法 def index_generator(L, target): for i, num in enumerate(L): if num == target: yield i print(list(index_generator([1, 6, 2, 4, 5, 2, 8, 6, 3, 2], 2))) ######### 輸出 ########## [2, 5, 9]
再看一例子:
查找子序列:給定兩個字符串a(chǎn),b,查找字符串a(chǎn)是否字符串b的子序列,所謂子序列,即一個序列包含在另一個序列中并且順序一
算法:分別用兩個指針指向兩個字符串的頭,然后往后移動找出相同的值,如果其中一個指針走完了整個字符串也沒有相同的值,則不是子序列
def is_subsequence(a, b): b = iter(b) return all(i in b for i in a) print(is_subsequence([1, 3, 5], [1, 2, 3, 4, 5])) print(is_subsequence([1, 4, 3], [1, 2, 3, 4, 5])) ######### 輸出 ########## True False
下面代碼為上面代碼的演化版本
def is_subsequence(a, b): b = iter(b) print(b) gen = (i for i in a) print(gen) for i in gen: print(i) gen = ((i in b) for i in a) print(gen) for i in gen: print(i) return all(((i in b) for i in a)) print(is_subsequence([1, 3, 5], [1, 2, 3, 4, 5])) print(is_subsequence([1, 4, 3], [1, 2, 3, 4, 5])) ########## 輸出 ########## # <list_iterator object at 0x000001E7063D0E80> # <generator object is_subsequence.<locals>.<genexpr> at 0x000001E70651C570> # 1 # 3 # 5 # <generator object is_subsequence.<locals>.<genexpr> at 0x000001E70651C5E8> # True # True # True # False # <list_iterator object at 0x000001E7063D0D30> # <generator object is_subsequence.<locals>.<genexpr> at 0x000001E70651C5E8> # 1 # 4 # 3 # <generator object is_subsequence.<locals>.<genexpr> at 0x000001E70651C570> # True # True # False # False
首先iter(b)把b轉(zhuǎn)為迭代器。目的是內(nèi)部實現(xiàn)next函數(shù),(i for i in a) 會產(chǎn)生一個生成器 ,同樣((i in b) for i in a)也是。然后(i in b)等階于:
while True: val = next(b) if val == i: yield True
這里非常巧妙地利用生成器的特性,next()函數(shù)運行的時候,保存了當(dāng)前的指針。比如下面這個示例
b = (i for i in range(5)) print(2 in b) print(4 in b) print(3 in b) ########## 輸出 ########## True True False
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- python 協(xié)程中的迭代器,生成器原理及應(yīng)用實例詳解
- Python迭代器iterator生成器generator使用解析
- python 生成器和迭代器的原理解析
- 詳解python中的生成器、迭代器、閉包、裝飾器
- 一篇文章弄懂Python中的可迭代對象、迭代器和生成器
- Python學(xué)習(xí)筆記之迭代器和生成器用法實例詳解
- 一篇文章徹底搞懂Python中可迭代(Iterable)、迭代器(Iterator)與生成器(Generator)的概念
- 淺談Python中的可迭代對象、迭代器、For循環(huán)工作機制、生成器
- Python通過for循環(huán)理解迭代器和生成器實例詳解
- 正確理解python迭代器與生成器
相關(guān)文章
PyTorch中的Subset類簡介與應(yīng)用示例代碼
在深度學(xué)習(xí)框架PyTorch中,torch.utils.data.Subset是一個非常有用的類,用于從一個較大的數(shù)據(jù)集中選擇一個子集,本文將介紹Subset的概念、基本用法以及一些實際應(yīng)用示例,感興趣的朋友一起看看吧2024-08-08
用django設(shè)置session過期時間的方法解析
這篇文章主要介紹了用django設(shè)置session過期時間的方法解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-08-08
使用tensorflow保存和恢復(fù)模型saver.restore
這篇文章主要介紹了使用tensorflow保存和恢復(fù)模型saver.restore方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-02-02
python Boltons庫實用功能探索(深度復(fù)制類型檢查重試機制)
這篇文章主要為大家介紹了python Boltons庫實用功能探索包含深度復(fù)制類型檢查重試機制及數(shù)據(jù)結(jié)構(gòu)轉(zhuǎn)換實現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2024-01-01
Python中基礎(chǔ)的socket編程實戰(zhàn)攻略
Python擁有內(nèi)置的socket模塊,可以用簡潔明了的代碼來進行socket通信操作,這里我們就為大家整理了一份Python中基礎(chǔ)的socket編程實戰(zhàn)攻略,需要的朋友可以參考下.2016-06-06

