搜索
首页后端开发Python教程python中5个常用的内置高阶函数的介绍(附代码)

本篇文章给大家带来的内容是关于python中5个常用的内置高阶函数的介绍(附代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

python内置常用高阶函数:

一、函数式编程

函数本身可以赋值给变量,赋值后变量为函数;

允许将函数本身作为参数传入另一个函数;

允许返回一个函数。

1、map()函数

是 Python 内置的高阶函数,它接收一个函数 f 和一个 list,

并通过把函数 f 依次作用在 list 的每个元素上,得到一个新的 list 并返回

def add(x):
    return x+x

print(map(add,[1, 2, 3]))
# Out:<map object at 0x00000239E833DE48>
print(list(map(add,[1, 2, 3])))
# Out:[2, 4, 6]

2、reduce()函数

reduce()函数也是Python内置的一个高阶函数。

reduce()函数接收的参数和 map()类似,一个函数 f,一个list,但行为和 map()不同,reduce()传入的函数f必须接收两个参数,

reduce()对list的每个元素反复调用函数f,并返回最终结果值。

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

则需要通过引入 functools 模块来调用 reduce() 函数:

from functools import reduce


def prod(x, y):
    return x*y


print(reduce(prod, [2, 4, 5, 7, 12]))
# Out:3360  # 2*4*5*7*12
# reduce()还可以接收第3个可选参数,作为计算的初始值。如果把初始值设为100
print(reduce(prod, [2, 4, 5, 7, 12], 100))
# Out:336000    # 2*4*5*7*12*100

3、filter()函数

是 Python 内置的另一个有用的高阶函数,filter()函数接收一个函数 f 和一个list,

这个函数f的作用是对每个元素进行判断,返回 True或 False,filter()根据判断结果自动过滤掉不符合条件的元素,

返回由符合条件元素组成的新list。

import math

def is_sqr(x):
    return math.sqrt(x) == int(math.sqrt(x))

print(list(filter(is_sqr, range(1, 101))))
# Out:[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

4、sorted() 函数

对所有可迭代的对象进行排序操作。

sort 与 sorted 区别:

sort 是应用在 list 上的方法,sorted 可以对所有可迭代的对象进行排序操作。

list 的 sort 方法返回的是对已经存在的列表进行操作,而内建函数 sorted 方法返回的是一个新的 list,而不是在原来的基础上进行的操作。

sorted(iterable, key=None, reverse=False)

iterable -- 可迭代对象。

key -- 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。

reverse -- 排序规则,reverse = True 降序 , reverse = False 升序(默认)。

返回重新排序的列表

print(sorted([5, 2, 3, 1, 4]))
# Out:[1, 2, 3, 4, 5]
print(sorted({1:&#39;D&#39;, 2:&#39;B&#39;, 3:&#39;B&#39;, 4:&#39;E&#39;, 5: &#39;A&#39;}))
# Out:[1, 2, 3, 4, 5]


利用key进行倒序排序

example_list = [5, 0, 6, 1, 2, 7, 3, 4]
result_list = sorted(example_list, key=lambda x: x*-1)
print(result_list)

要进行反向排序,也可以通过传入第三个参数 reverse=True:

example_list = [5, 0, 6, 1, 2, 7, 3, 4]
print(sorted(example_list, reverse=True))
# Out:[7, 6, 5, 4, 3, 2, 1, 0]

5、Python的函数不但可以返回int、str、list、dict等数据类型,还可以返回函数!

请注意区分返回函数和返回值:

def my_abs():
    return abs  # 返回函数,返回函数可以把一些计算延迟

def my_abs2(x):
    return abs(x)   # 返回函数调用的结果,返回值是一个数值
def calc_prod(lst):
    def lazy_prod():
        prod = 1
        for i in lst:
            prod = prod*i
        return prod
    return lazy_prod
f = calc_prod([1, 2, 3, 4])
print(f())
# Out:24

5.1、为什么定义lazy_prod()函数和返回函数cal_prod()?

python支持返回函数的基本语法

def f():
    print(&#39;call f()...&#39;)
    # 定义函数g:
    def g():
        print(&#39;call g()...&#39;)
    # 返回函数g:
    return g

只返回函数的作用:

返回函数可以把一些计算延迟执行。例如,如果定义一个普通的求和函数:

def calc_sum(lst):
    return sum(lst)
print(calc_sum([1,2,3,4]))
# Out:10

def calc_sum(lst):
    def lazy_sum():
        return sum(lst)
    return lazy_sum

f = calc_sum([1, 2, 3, 4])
print(f)    # 代码并没有对函数进行执行计算出结果,而是返回函数,所以打印出来的是类型
#Out: <function calc_sum.<locals>.lazy_sum at 0x000001FF43462E18>
print(f())      # 对返回的函数进行调用时,才计算出结果
# Out:10

以上是python中5个常用的内置高阶函数的介绍(附代码)的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:segmentfault。如有侵权,请联系admin@php.cn删除
Python的混合方法:编译和解释合并Python的混合方法:编译和解释合并May 08, 2025 am 12:16 AM

pythonuseshybridapprace,ComminingCompilationTobyTecoDeAndInterpretation.1)codeiscompiledtoplatform-Indepententbybytecode.2)bytecodeisisterpretedbybythepbybythepythonvirtualmachine,增强效率和通用性。

了解python的' for”和' then”循环之间的差异了解python的' for”和' then”循环之间的差异May 08, 2025 am 12:11 AM

theKeyDifferencesBetnewpython's“ for”和“ for”和“ loopsare:1)” for“ loopsareIdealForiteringSequenceSquencesSorkNowniterations,而2)”,而“ loopsareBetterforConterContinuingUntilacTientInditionIntionismetismetistismetistwithOutpredefinedInedIterations.un

Python串联列表与重复Python串联列表与重复May 08, 2025 am 12:09 AM

在Python中,可以通过多种方法连接列表并管理重复元素:1)使用 运算符或extend()方法可以保留所有重复元素;2)转换为集合再转回列表可以去除所有重复元素,但会丢失原有顺序;3)使用循环或列表推导式结合集合可以去除重复元素并保持原有顺序。

Python列表串联性能:速度比较Python列表串联性能:速度比较May 08, 2025 am 12:09 AM

fasteStmethodMethodMethodConcatenationInpythondependersonListsize:1)forsmalllists,operatorseffited.2)forlargerlists,list.extend.extend()orlistComprechensionfaster,withextendEffaster,withExtendEffers,withextend()withextend()是extextend()asmoremory-ememory-emmoremory-emmoremory-emmodifyinginglistsin-place-place-place。

您如何将元素插入python列表中?您如何将元素插入python列表中?May 08, 2025 am 12:07 AM

toInSerteLementIntoApythonList,useAppend()toaddtotheend,insert()foreSpificPosition,andextend()formultiplelements.1)useappend()foraddingsingleitemstotheend.2)useAddingsingLeitemStotheend.2)useeapecificindex,toadapecificindex,toadaSpecificIndex,toadaSpecificIndex,blyit'ssssssslorist.3 toaddextext.3

Python是否列表动态阵列或引擎盖下的链接列表?Python是否列表动态阵列或引擎盖下的链接列表?May 07, 2025 am 12:16 AM

pythonlistsareimplementedasdynamicarrays,notlinkedlists.1)他们areStoredIncoNtiguulMemoryBlocks,mayrequireRealLealLocationWhenAppendingItems,EmpactingPerformance.2)LinkesedlistSwoldOfferefeRefeRefeRefeRefficeInsertions/DeletionsButslowerIndexeDexedAccess,Lestpypytypypytypypytypy

如何从python列表中删除元素?如何从python列表中删除元素?May 07, 2025 am 12:15 AM

pythonoffersFourmainMethodStoreMoveElement Fromalist:1)删除(值)emovesthefirstoccurrenceofavalue,2)pop(index)emovesanderturnsanelementataSpecifiedIndex,3)delstatementremoveselemsbybybyselementbybyindexorslicebybyindexorslice,and 4)

试图运行脚本时,应该检查是否会遇到'权限拒绝”错误?试图运行脚本时,应该检查是否会遇到'权限拒绝”错误?May 07, 2025 am 12:12 AM

toresolvea“ dermissionded”错误Whenrunningascript,跟随台词:1)CheckAndAdjustTheScript'Spermissions ofchmod xmyscript.shtomakeitexecutable.2)nesureThEseRethEserethescriptistriptocriptibationalocatiforecationAdirectorywherewhereyOuhaveWritePerMissionsyOuhaveWritePermissionsyYouHaveWritePermissions,susteSyAsyOURHomeRecretectory。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境