如何使用filter ,map,以及混合使用lambda简化操作

#!/usr/bin/env python3

-*- coding: utf-8

如何使用filter ,map,以及混合使用lambda简化操作

首先讲一下lambda的用法和举例

nambers = [1,2,3,4,5,6,7,8,9]
def calculate(x):
    return filter(lambda x : x %2 == 0,nambers)
calculate(nambers)
b= lambda x: x + x
print(b(2))
print(lambda x:x +x(2))
#L列表推导式
a =[i for i in range(100) if not(i % 2) and (i % 3)]
c = [i for i in nambers if not(i % 2 )]
print(c)
def k (s):
    return s % 2 == 0
print (list((filter(k,nambers))))
nums = [2,3,6,12,15,18]

***这里开始讲map 和filter的作用
注意:这是很重要的一个点,要不然出来的一个电脑识别的,人类可是无法读取的哦

map和filter返回的是一个对象,所以要用list转成一个列表


def nums_res (x):
  return x % 2==0  and x % 3==0

filter顾名思义,就是一个过滤器.使得满足条件的数字可以过去,返回出来

print(list(filter(nums_res, nums)))

这里用lambda,简化过程和操作量,其实实质和上面的是一样的,


**#**
print(list(filter(lambda x: x % 2 == 0 ,nambers)))
print(list(map(lambda x:x * x,nambers)))

下面附完整的代码:

nambers = [1,2,3,4,5,6,7,8,9]
def calculate(x):
    return filter(lambda x : x %2 == 0,nambers)
calculate(nambers)
b= lambda x: x + x
print(b(2))
print(lambda x:x +x(2))
#L列表推导式
a =[i for i in range(100) if not(i % 2) and (i % 3)]
c = [i for i in nambers if not(i % 2 )]
print(c)
def k (s):
    return s % 2 == 0
print (list((filter(k,nambers))))
nums = [2,3,6,12,15,18]
#因为map和filter返回的是一个对象,所有要用list转成一个列表
def nums_res (x):
  return x % 2==0  and x % 3==0
#filter顾名思义,就是一个过滤器.使得满足条件的数字可以过去,返回出来
print(list(filter(nums_res, nums)))

print(list(filter(lambda x: x % 2 == 0 ,nambers)))
print(list(map(lambda x:x * x,nambers)))
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值