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
廣告