python之lambda表达式,filter过滤器,map

  • lambda表达式
g = lambda x, y: x * y
print(g(2, 3))

其中x, y是参数, 这是一个匿名函数,用g来接收

运行结果

6
  • filter过滤器
print(filter(None , [1,2,True, False,0,5]))
print(list(filter(None , [1,2,True, False,0,5])))

运行结果

<filter object at 0x000002ED570EE748>
[1, 2, True, 5]

可见filter()返回的是可迭代的对象
同时功能是将为false的值过滤掉
看到这里我们看一下filter的帮助文档

class filter(object)
| 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的第一个参数可以是一个function
那接下来我来定义一个返回奇数的方法

def odd(x):
    return x % 2


print(filter(odd, range(10)))
print(list(filter(odd, range(10))))

运行结果

<filter object at 0x00000299109CE908>
[1, 3, 5, 7, 9]

将上面的用lambda表达式实现

print(filter(lambda x: x % 2, range(10)))
print(list(filter(lambda x: x % 2, range(10))))

运行结果同上

  • map()
print(map(lambda x: x * 2, range(10)))
print(list(map(lambda x: x * 2, range(10))))

运行结果

<map object at 0x00000210AE658F08>
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

云风Com

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

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

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

打赏作者

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

抵扣说明:

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

余额充值