#!/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)))