filter用法

filter()函数是python中的一个内置函数,用于过滤序列,生成包含满足不二条件的项的新可迭代对象。

1.找出列表[4,9,3,14,7,10,6,1]的奇数

方法一:

1     L = [4,9,3,14,7,10,6,1]
2     def is_odd(x):
3         return x % 2 == 1
4     newlist = list(filter(is_odd,L))
5     print(newlist)  #[9, 3, 7, 1]

方法二:

1   L = [4,9,3,14,7,10,6,1]
2   newlist = list(filter(lambda x:x%2==1,L))
3     print(newlist)  #[9, 3, 7, 1]

 方法三(未使用filter):

1   res = [i for i in L if i % 2 == 1]

 

 

 

 

放下个人素质,享受缺德人生。

posted @ 2023-02-01 18:43  心如__止水  阅读(127)  评论(0编辑  收藏  举报