itertools 库中的 tee() 函数

这是一个从列表中获取最小值、最大值和平均值的简单示例。下面的两个函数有相同的结果。我想知道这两个函数之间的区别。为什么要使用itertools.tee()?它提供了什么优势?


from statistics import median

from itertools import tee


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)


def main():

    stats = process_purchases(purchases=purchases)

    print("Result:", stats)

    stats = _process_purchases(purchases=purchases)

    print("Result:", stats)


if __name__ == '__main__':

    main()


aluckdog
浏览 140回答 1
1回答

MYYA

迭代器在 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 teefrom statistics import medianpurchases = [1, 2, 3, 4, 5]def process_purchases(purchases):&nbsp; &nbsp; min_, max_, avg = tee(purchases, 3)&nbsp; &nbsp; return min(min_), max(max_), median(avg)def _process_purchases(purchases):&nbsp; &nbsp; return min(purchases), max(purchases), median(purchases)double = map(lambda n: n*2, purchases)_process_purchases(double)# ValueError: max() arg is an empty sequencedouble = map(lambda n: n*2, purchases)process_purchases(double)# (2, 10, 6)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python