python常用的几个内建函数

学习版本3.5.2

1.map()函数

help(map)查看map的帮助文档

map(func, *iterables) --> map object

Make an iterator that computes the function using arguments from each of the iterables.  Stops when the shortest iterable is exhausted.

map将func作用到每一个*iterables的元素,返回的是一个map对象

map(lambda x:x, range(1,3)
#<map object at 0x1013e44a8> #3.5版本
#[1, 2] #2.7版本
可以直接用list将map对象转化为list

list(map(lambda x:x, range(1,3)))
#[1, 2]

2.filter函数

同样用help来查看帮助文档

filter(function or None, iterable) --> filter object
Return an iterator yielding those items of iterable for which function(item) is true. If function is None, return the items that are true.

filter筛选出能使fun返回true的元素,返回的是一个filter对象

同样能用list将filter转化为list

filter(lambda x:x>0, range(-5,5))
#<filter object at 0x1013ed550>
list(filter(lambda x:x>0, range(-5,5)))
#[1, 2, 3, 4]

3.reduce函数

在3.5.2中,reduce函数在functools模块里面

查看帮助文档

reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a 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).  If initial is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty.

reduce的fun必须要两个参数,把每次func的计算结果都与下一个元素继续进行计算,最后返回一个值

import functools
functools.reduce(lambda x,y:x*y, range(1,5))
#24



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值