Python 中的过滤器
pythonserver side programmingprogramming更新于 2025/10/19 7:08:17
我们有时会遇到这样的情况:我们有两个列表,我们想检查较小列表中的每个项目是否存在于较大列表中。在这种情况下,我们使用下面讨论的 filter() 函数。
语法
Filter(function_name, 序列名称)
此处 Function_name 是具有过滤条件的函数的名称。序列名称是具有需要过滤的元素的序列。它可以是集合、列表、元组或其他迭代器。
示例
在下面的示例中,我们获取一些月份名称的较大列表,然后过滤掉那些没有 30 天的月份。为此,我们创建一个较小的列表,其中包含 31 天的月份,然后应用过滤函数。
# 月份列表
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul','Aug']
# 过滤某些月份的函数
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
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

