本人只是初学阶段,在学习过程中的一些笔记。想借此平台也分享给刚刚学习的朋友,如有错的地方欢迎各位大神与高手指点。
在 Python3 中,reduce() 函数已经被从全局名字空间里移除了,它现在被放置在 functools 模块里,
如果想要使用它,则需要通过引入 functools 模块来调用 reduce() 函数
from functools import reduce
例子一:将1~10各个数相加,得出结果
from functools import reduce
def f1(x, y):
return x + y
l1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(reduce(f1, l1))
或者
from functools import reduce
def total(x, y):
return x + y
print(reduce(total, range(1, 11)))
例子二:统计某字符串出现次数
from functools import reduce
sentences = [
'The Deep Learning textbook is a resource intended to help students and practitioners enter the field of machine learning in general and deep learning in particular. ']
word_count = reduce(lambda a, x: a + x.count("learning"), sentences, 0)
print(word_count)
或者
sentences = ['The Deep Learning textbook is a resource intended to help students and practitioners enter the field of machine learning in general and deep learning in particular. ']
print(sentences[0].count('learning'))
网友评论