Python攻关之函数第四篇

本文介绍了Python的内置函数,包括abs、all、eval、filter、map和reduce等,讲解了它们的功能和使用示例。特别是lambda表达式与Reduce函数的结合,用于实现计算阶乘。内容是作者学习过程中的个人笔记,适合初学者参考。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

04内置函数


之前我们学习了根据实际情况的需求去自定义函数,实际上python官方库为我们提供了丰富的内置函数,可以根据其功能直接调用相关的内置函数。

                                                 python官方内置函数库

                                                                                                                 Built-in Functions
abs()delattr()hash()memoryview()set()
all()dict()help()min()setattr()
any()dir()hex()next()slice()
ascii()divmod()id()object()sorted()
bin()enumerate()input()oct()staticmethod()
bool()eval()int()open()str()
breakpoint()exec()isinstance()ord()sum()
bytearray()filter()issubclass()pow()super()
bytes()float()iter()print()tuple()
callable()format()len()property()type()
chr()frozenset()list()range()vars()
classmethod()getattr()locals()repr()zip()
compile()globals()map()reversed()__import__()
complex()hasattr()max()round() 


内置函数中有关于类的函数,后面介绍’‘类‘’这个知识点时会重点介绍,现在先介绍其它一些重要常见的内置函数的作用。

abs(x)
Return the absolute value of a number.The argument may be an integer or a floating point number.
If the argument is a complex number, its magnitude is returned.
If x defines __abs__(), abs(x) returns x.__abs__().

# 绝对值输出 ; 当式子中运算时自动计算结果并输出绝对值
print(abs(-2))      #2
print(abs(-2-3+1))  #4

all(iterable)
Return True if all elements of the iterable are true (or if the iterable is empty).

# 当有字符或者空格时返回Ture
print(all((1,2,"xiao")))   #True
print(all((1,2,"")))       #False
print(all((1,2," ")))      #True
print(all((1,2, )))        #True

eval(expression[, globals[, locals]])
The return value is the result of the evaluated expression.

#返回计算式子的结果
x = 1
print(eval('x+1'))         #2

重要的内置函数*****

filter(function, sequence)  (功能函数的变量名,可迭代)
对sequence中的item
依次执行function(item),将执行结果为True的item做成一个filter object的迭代器返回。可以看作是过滤函数

str = ['a','b','c','d']
def func(s):
    if s != 'a':
        return s
ret_1 = filter(func,str)   #('b', 'c', 'd')   <filter object at 0x0000021FA87C7F70>
print(ret_1)
ret_2 = list(ret_1)        #['b', 'c', 'd'],利用list强转为列表
print(ret_2)

 


map(function, sequence)  (功能函数的变量名,可迭代,... )
对sequence中的item依次执行function(item),将
执行结果(可以修改)组成一个map object迭代器返回.    (与filter函数最大的区别)
map也支持多个sequence,这就要求function也支持相应数量的参数输入

str_2 = ['a','b','c']
def func_2(s):
    return s + 'VXVX'
ret_3 = map(func_2,str_2)  #('aVXVX', 'bVXVX', 'cVXVX')  <map object at 0x0000017987CB7F70>
print(ret_3)
ret_4 = list(ret_3)        #['aVXVX', 'bVXVX', 'cVXVX']
print(ret_4)
def add(x,y):
    return x+y
ret_5 = map(add,range(10),range(10))   #(0, 2, 4, 6, 8, 10, 12, 14, 16, 18)  <map object at 0x00000256759C7670>
print(ret_5)
ret_6 = list(ret_5)                    #[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]  可以利用此输出连续偶数
print(ret_6)

 


reduce(function, sequence, starting_value)

有starting_value,还可以作为初始值调用

from functools import reduce         #reduce的调用方法
def func_3(x,y):
    return x+y
ret_3 = reduce(func_3,range(1,11))   #reduce函数实现累加(两两处理),即1+2=3,3+3=6,6+4=10.....
print(ret_3)                         #55

 


 

lambda
匿名函数的命名规则,用lamdba关键字标识,格式 :左侧表示函数接收的参数a,b ; :右侧表示代码块
lambda在创建时不需要命名

add = lambda x,y : x+y   #add为一个自定义的函数
print(add(3,4))          #7

Reduce函数结合lambda表达式式实现阶乘

from functools import reduce
result = reduce((lambda x,y :x*y),range(1,6))   #1*2*3*4*5
print(result)                                   #120


这些是个人在学习过程中整理的笔记,仅供参考!欢迎大家指正和提问!整理不容易,花了不少时间,后续会接着整理,要是觉得好对您有用还请不要忘了点赞收藏转发+关注哦🤞🤞🤞

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

VX@

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值