python基础——匿名函数

lambda匿名函数可以实现简单的功能:

sum=lambda x,y:x+y
print(sum(4,2))                         #结果为6
def values(a,b,fun):
   print(fun(a,b))
values(11,22,lambda x,y:x+y)            #结果为33

大数据要用到的三个重要函数:

filter函数: filter()主要用来筛选。输出filter的时候前边需要加上星号。

list1=[1,2,3,4,5,6,7,8,9,10]
print(*filter(lambda x:x<6,list1))     #输出结果 1 2 3 4 5 
list2=filter(lambda x:x%2,list1)
for i in list2:
    print(i)                           #输出结果 1 3 5 7 9  
def is_not_empty(s):
 return s and len(s.strip()) > 0       #结果为test str END
print(*filter(is_not_empty, ['test', None, '', 'str', ' ', 'END']))   #去除列表中的空格和空字符

map函数:map()传入两个参数,一个是函数一个是序列。map将函数作用到序列的每个元素并返回新的list列表。

list1=[3,4,5,6,7,8,9,10]
list2=map(lambda x:x+10,list1)
for i in list2:
  print(i,end=" ")                     #结果为13 14 15 16 17 18 19 20 

reduce函数:reduce()是对列表,元组中的数据进行累计的函数

from functools import reduce
#需要先导入reduce模块 
list1=[1,2,3,4,5,6,7,8,9,10]
print(reduce(lambda x,y:x+y,list1))    #结果为55




猜你喜欢

转载自blog.csdn.net/pythonzyj/article/details/80690815
今日推荐