[Python3]from functools import reduce

 

提醒:在python3中,reduce被移到了functools里面

 

from functools import reduce
str1 = 'the quick brown fox'
str2 = ' jumps over '
str3 = 'the lazy dog.'

print(reduce(lambda a, b: a+b, [str1, str2, str3]))

 

输出结果为:

the quick brown fox jumps over the lazy dog.

 

 

如果计算1+2+3+...+100=?

同样可以使用reduce

 

from functools import reduce
print(reduce((lambda a,b: a+b), [i for i in range(1, 101)]))

 

输出结果为:

5050

 

posted @ 2020-06-02 19:09  profesor  阅读(1237)  评论(0编辑  收藏  举报