簡體   English   中英

Python - 多條件過濾函數

[英]Python - Filter function with multiple conditions

我知道這是一個愚蠢的問題,但我沒有按照我的想法在這里找到答案

我只想知道是否可以在單個filter功能中應用多個過濾filter

一個簡單的代碼來試試:

def check_odd(x):

    return (x % 2) == 0

l1 = list(range(1,20))
list(filter((check_odd and lambda x:x>=5), l1))

使用上面的代碼只應用了一個過濾器(第二個)。

我使用以下方法解決了它:

list(filter(check_odd, filter(lambda x:x>=5, l1)))

但我想知道是否有辦法將過濾器功能中的所有過濾器分組。

剛剛改造and內部lamda ,並有結合您的情況:

def check_odd(x):
    return (x % 2) == 0

l1 = list(range(1,20))
l2 = list(filter((lambda x:x>=5 and check_odd(x)), l1))
print(l2)

更新
實際上,您可以通過將其他函數中的任意數量的條件都包裝在 lambda 中來組合它們。 下面是一個例子:

def check_odd(x):
    return (x % 2) == 0

def check_greater_than_five(x):
    return x >= 5

def check_divisible_by_three(x):
    return x % 3 == 0

l1 = list(range(1,20))
l2 = list(filter((lambda x: (check_odd(x) or check_divisible_by_three(x)) and check_greater_than_five(x)), l1))
print(l2)   #prints all numbers that are greater than five, and are divisible by either 2 or 3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM