标准库中的生成器函数——用于映射的生成器函数

发布时间 2023-05-20 13:57:00作者: limalove

 

 

aa

 

 1 #演示itertools.accumulate生成器函数
 2 
 3 import itertools
 4 import operator
 5 
 6 
 7 sample = [5, 4, 2, 8, 7, 6, 3, 0, 9, 1]
 8 
 9 e1 = list(itertools.accumulate(sample))
10 print("默认求累计和:", e1)  #[5, 9, 11, 19, 26, 32, 35, 35, 44, 45]
11 
12 e2= list(itertools.accumulate(sample, min))
13 print("传递min函数,求累计结果:", e2)  #[5, 4, 2, 2, 2, 2, 2, 0, 0, 0]
14 
15 e3 = list(itertools.accumulate(sample, max))
16 print("传递max函数,求累计结果:", e3)  #[5, 5, 5, 8, 8, 8, 8, 8, 9, 9]
17 
18 
19 e4 = list(itertools.accumulate(sample, operator.mul))
20 print("传递operator.mul函数,求累计结果:", e4)  #[5, 20, 40, 320, 2240, 13440, 40320, 0, 0, 0]
21 
22 e5 = list(itertools.accumulate(range(1,11), operator.mul))
23 print("累计结果:", e5)  # [1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]

 

 

 

ff