菜鸟教程 -- 学的不仅是技术,更是梦想!

Python 基础教程
(追記) (追記ここまで)

Python reduce() 函数

Python 内置函数 Python 内置函数


描述

reduce() 函数会对参数序列中元素进行累积。

函数将一个数据集合(链表,元组等)中的所有数据进行下列操作:用传给 reduce 中的函数 function(有两个参数)先对集合中的第 1、2 个元素进行操作,得到的结果再与第三个数据用 function 函数运算,最后得到一个结果。

注意:Python3.x reduce() 已经被移到 functools 模块里,如果我们要使用,需要引入 functools 模块来调用 reduce() 函数:

from functools import reduce

语法

reduce() 函数语法:

reduce(function, iterable[, initializer])

参数

  • function -- 函数,有两个参数
  • iterable -- 可迭代对象
  • initializer -- 可选,初始参数

返回值

返回函数计算结果。

实例

以下实例展示了 reduce() 的使用方法:

实例(Python 2.x)

#!/usr/bin/python
# -*- coding: UTF-8 -*-

def add(x, y) : # 两数相加
return x + y
sum1 = reduce(add, [1,2,3,4,5]) # 计算列表和:1+2+3+4+5
sum2 = reduce(lambda x, y: x+y, [1,2,3,4,5]) # 使用 lambda 匿名函数
print(sum1)
print(sum2)

实例(Python 3.x)

#!/usr/bin/python
from functools import reduce

def add(x, y) : # 两数相加
return x + y
sum1 = reduce(add, [1,2,3,4,5]) # 计算列表和:1+2+3+4+5
sum2 = reduce(lambda x, y: x+y, [1,2,3,4,5]) # 使用 lambda 匿名函数
print(sum1)
print(sum2)

以上实例输出结果为:

15
15

Python 内置函数 Python 内置函数

AI 思考中...

3 篇笔记 写笔记

  1. #0

    不梦君

    411***[email protected]

    36

    在 Python3 中,reduce() 函数已经被从全局名字空间里移除了,它现在被放置在 functools 模块里,如果想要使用它,则需要通过引入 functools 模块来调用 reduce() 函数:

    from functools import reduce

    实例:

    from functools import reduce
    def add(x,y):
     return x + y
    print (reduce(add, range(1, 101)))

    输出结果为:

    5050
    不梦君

    不梦君

    411***[email protected]

    8年前 (2018年04月30日)
  2. #0

    763***[email protected]

    13

    Python3 统计某字符串重复次数:

    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)

    输出结果为:

    2

    当然,如果只是单纯实现功能可以使用以下方式:

    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. '] 
    print(sentences[0].count('learning'))

    763***[email protected]

    8年前 (2018年06月14日)
  3. #0

    见不如念

    134***[email protected]

    45
    import functools
    str1="hello"
    print(functools.reduce(lambda x,y:y+x,str1))
    # 输出 olleh
    

    见不如念

    134***[email protected]

    7年前 (2019年03月09日)

点我分享笔记

  • 昵称 (必填)
  • 邮箱 (必填)
  • 引用地址

AltStyle によって変換されたページ (->オリジナル) /