# itertools 库中的 tee() 函数

2022-11-24 15:03:04

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()

## 1 回答

MYYA

TA贡献1588条经验 获得超4个赞

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

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)

• 1 回答
• 0 关注
• 13 浏览

0/150