1 回答

TA貢獻(xiàn)1868條經(jīng)驗(yàn) 獲得超4個(gè)贊
迭代器在 python 中只能迭代一次。之后,它們“耗盡”并且不再返回更多值。
map()您可以在、和許多其他函數(shù)zip()中看到這一點(diǎn):filter()
purchases = [1, 2, 3, 4, 5]
double = map(lambda n: n*2, purchases)
print(list(double))
# [2, 4, 6, 8, 10]
print(list(double))
# [] <-- can't use it twice
如果將迭代器傳遞給兩個(gè)函數(shù),例如 的返回值,您可以看到它們之間的區(qū)別map()。在這種情況下_process_purchases()失敗,因?yàn)橛帽M了迭代器并且沒有為和min()留下任何值。max()median()
tee()接受一個(gè)迭代器并給你兩個(gè)或更多,允許你多次使用傳遞給函數(shù)的迭代器:
from itertools import tee
from statistics import median
purchases = [1, 2, 3, 4, 5]
def process_purchases(purchases):
min_, max_, avg = tee(purchases, 3)
return min(min_), max(max_), median(avg)
def _process_purchases(purchases):
return min(purchases), max(purchases), median(purchases)
double = map(lambda n: n*2, purchases)
_process_purchases(double)
# ValueError: max() arg is an empty sequence
double = map(lambda n: n*2, purchases)
process_purchases(double)
# (2, 10, 6)
添加回答
舉報(bào)