Python 中的 Filter
有时我们会遇到这样的情况:我们有两份清单,并且我们想检查较小清单中的每个项目是否出现在较大清单中。在这种情况下,我们会使用如下讨论的 filter() 函数。
语法
Filter(function_name, sequence name)
此处 Function_name 是具有筛选条件的函数的名称。序列名称是要筛选元素的序列。它可以是集合、列表、元组或其他迭代器。
示例
在下面的示例中,我们取一个较大月份名称列表,然后过滤掉没有 30 天的月份。为此,我们创建了一个包含 31 天月份的小型列表,然后应用筛选功能。
# list of Months
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul','Aug']
# function that filters some Months
def filterMonths(months):
MonthsWith31 = ['Apr', 'Jun','Aug','Oct']
if(months in MonthsWith31):
return True
else:
return False
non30months = filter(filterMonths, months)
print('The filtered Months :')
for month in non30months:
print(month)输出
运行上述代码会产生以下结果 -
The filtered Months : Apr Jun Aug
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP