您的位置:首页 > 编程语言 > Python开发

python自学笔记6之库函数

2016-09-20 22:15 501 查看
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])


确定算法的条件下,实现方式的不一样,代码执行效率不一样!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python