用Python过滤
有时我们遇到两个列表的情况,我们想检查较小列表中的每个项目是否存在于较大列表中。在这种情况下,我们使用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
热门推荐
10 诗词送行祝福语大全简短
11 新房开工吉日祝福语简短
12 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短