python3 常见函数 map、reduce、filter、lambda、sorted

函数 map、reduce、filter、lambda、sorted

映射函数 map

map(function, iterable, …)

function 函数
iterable 一个或多个可迭代对象

其最终的返回结果,是一个列表

def squar(x):
    return x ** 2

list(map(squar,[1,2,3,4,5]))
[1, 4, 9, 16, 25]

reduce() 函数

reduce() 函数已经从内置函数中移除,需要先 import

from functools import reduce

语法:

reduce(function, iterable[, initializer])

function 函数,必须有两个参数
iterable 可迭代对象
initializer 初始参数

from functools import reduce

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

print(reduce(test,[1,2,3,4,5,6], 1000))

第一次调用 test 函数,传入 1 和 2

第二次,将第一次的函数返回值作为第一个参数,和第三个参数一起传入函数,以此类推

最后再把 initializer 初始参数传入函数

filter() 过滤

语法:

filter(function, iterable)

function 判断函数,过滤条件
iterable 可迭代对象,被过滤的对象

def is_even(x):
    return x % 1 == 0

print(filter(is_even, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))

匿名函数 lambda

python 用 lambda 来创建匿名函数。对于一些比较抽象并且整个程序执行下来只需要调用一两次的函数,有时候给函数起个名字不如直接使用 lambda。

lambda 函数拥有自己的命名空间,且不能访问自有参数列表之外或全局命名空间里的参数。

语法

lambda [arg1 [,arg2,.....argn]]:expression

arg 即函数内的参数
expression 为函数内的函数体
>>> g = lambda x : 2 * x + 1
>>> g(5)
11

>>> count = lambda x,y : print (x,y)
>>> count(3,9)
(3,9)

sorted() 函数

执行结果,返回一个新的排过序的列表

sorted(iterable[, cmp[, key[, reverse]]])

iterable 可迭代对象

cmp 自定义的用来比较的函数,必须两个参数,此函数必须遵守的规则为,第一个参数大于第二个参数返回1,小于则返回-1,等于则返回0。

key 定制一个函数,调用 iterable 里面指定的元素,用来比较的关键字。

reverse 排序规则,True 降序,False 默认升序

使用 key 用来排序

devops = [('wangbin', 'ops', 91), ('zhouheng', 'ops' ,91), \
          ('xueming','dev',94), ('yanyixiao', 'dev', 95)]

print(sorted(devops, key=lambda x: x[2], reverse=True))
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值