python自学笔记6之库函数

本文介绍了Python中的reduce函数,包括其使用方法及如何通过官方文档找到所需函数的位置。同时提供了几个实用示例,如回文数判断等。

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

Python 3.5
reduce()函数是需要导入的:

from functools import reduce

那么问题来了?
从什么地方知道某个想用的函数在哪个库中躲藏着呢?

先来看看有哪些内置函数
内建函数
可以通过dir()和help()来查看内置函数
dir()可以看看模块里有什么函数,变量,嵌套的模块
help()可以看看函数的帮助文档
用过matlab的应该就知道了

那,这里没有的话,再去哪找?
https://docs.python.org/3/library/functools.html?highlight=reduce#functools.reduce
查找官方文档,search一下,你就知道
我搜索了reduce,结果如下

functools.reduce(function, iterable[, initializer])
Apply function of two arguments cumulatively to the items of sequence, from left to right, so as to reduce the sequence to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). The left argument, x, is the accumulated value and the right argument, y, is the update value from the sequence. If the optional initializer is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty. If initializer is not given and sequence contains only one item, the first item is returned.

Roughly equivalent to:

def reduce(function, iterable, initializer=None):
it = iter(iterable)
if initializer is None:
value = next(it)
else:
value = initializer
for element in it:
value = function(value, element)
return value

可以确定两点
1. functools.reduce,可以看到reduce 是functools里面的,所以 from functools import reduce,是可以用的
2. 说明文档中,你可以看到reduce函数的具体了,这样自己也能定义一个用,二手打算。

写了个回数判断函数:

def zis_palindrome(s1):
    s=list(str(s1))
    for i in range(len(s)):
        st=s[i]
        s[i]=s[len(s)-i-1]
        s[len(s)-i-1]=st
    return list(str(s1))==s

如果用到函数的话,一行代码就解决了!

def zis_palindrome(s1):
    return list(str(s))==list(reversed(str(s)))

当然,也有不用函数的高级版本

def is_palindrome(n):
    return n == int(str(n)[::-1])

确定算法的条件下,实现方式的不一样,代码执行效率不一样!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Z_shsf

来包瓜子嘛,谢谢客官~

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

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

打赏作者

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

抵扣说明:

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

余额充值