一、lambda表达式
lambda 表达式又称匿名函数,如果一个函数的函数体仅有 1 行表达式,则该函数就可以用 lambda 表达式来代替
对于单行函数,使用 lambda 表达式可以省去定义函数的过程让代码更加简洁;
对于不需要多次复用的函数,使用 lambda 表达式可以在用完之后立即释放,提高程序执行的性能。
语法格式是:
name = lambda [list] : 表达式
必须使用 lambda 关键字
[list] 作为可选参数等同于定义函数是指定的参数列表
def add(x, y):
return x+ y
print(add(3,4))
add = lambda x,y:x+y
print(add(3,4))
二、map
class map(object)
| 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.
将可迭代对象的元素依次取出来传给前面的函数对象func,来完成该函数的计算,这个函数对象也可以是lambda表达式
可迭代对象可以是多个,一般情况下可迭代对象的个数和函数所需要的参数个数一致
返回值是一个map对象 需要通过列表解析或者list()转换读取
>>> m= map(lambda x:x+3,range(10))
>>> m
<map object at 0x02F17B30>
>>> list(m)
[3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
通过list()转换查看map的内容
当然也可以用列表解析
>>> [i for i in m]
[3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
listDemo = [1, 2, 3, 4, 5]
new_list = map(lambda x,y: x-y>0,[3,5,6],[1,5,8] )
print(list(new_list))
运行结果为:
[True, False, False]
>>> lst1=[1,2,3,4]
>>> lst2=[5,6,7,8]
>>> lst3=[9,8,7,6]
>>> [x+y+z for x,y,z in zip(lst1,lst2,lst3)] 列表解析+zip实现对应位置元素相加
[15, 16, 17, 18]
>>> [i for i in map(lambda x,y,z:x+y+z,lst1,lstt2,lst3)] 列表解析+map+lambda实现
[15, 16, 17, 18]
三、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() 函数的功能是对 iterable 中的每个元素,都使用 function 函数判断,并返回 True 或者 False,最后将返回 True 的元素组成一个新的可遍历的filter对象。
过滤可迭代对象中的元素不满足函数funtion的那些值 即
返回可迭代对象中满足函数funtion的那些元素所构成的过滤器filter对象
参数iterator可迭代对象只能是一个
函数为空值None,返回的元素是可迭代器中所有为真的元素
>>> f=filter(lambda x:x>0,range(-5,5))
>>> list(f)
[1, 2, 3, 4]
>>> [i for i in filter(lambda x:x>0,range(-5,5))]
[1, 2, 3, 4]
>>> [i for i in filter(None,range(-5,5))]
[-5, -4, -3, -2, -1, 1, 2, 3, 4]
def getPyFile2(fileName):
if ".py" in fileName:
return fileName
else:
pass
fileNames=['a.py','b.cpp','c.py']
f=filter(getPyFile2,fileNames)
print(list(f))
运行结果
['a.py', 'c.py']
listDemo = [1, 2, 3, 4, 5]
new_list = filter(lambda x: x % 2 == 0, listDemo)
print(list(new_list))
运行结果为:
[2,4]