1 回答
TA贡献1868条经验 获得超4个赞
迭代器在 python 中只能迭代一次。之后,它们“耗尽”并且不再返回更多值。
map()您可以在、和许多其他函数zip()中看到这一点: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
如果将迭代器传递给两个函数,例如 的返回值,您可以看到它们之间的区别map()。在这种情况下_process_purchases()失败,因为用尽了迭代器并且没有为和min()留下任何值。max()median()
tee()接受一个迭代器并给你两个或更多,允许你多次使用传递给函数的迭代器:
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)
添加回答
举报