Multiple value checks using 'in' operator (Python)

前端 未结 7 1655
我寻月下人不归
我寻月下人不归 2020-11-29 07:37
if \'string1\' in line: ...

... works as expected but what if I need to check multiple strings like so:

if \'string1\' or \'string2         


        
相关标签:
7条回答
  • 2020-11-29 08:30

    Using map and lambda

    a = ["a", "b", "c"]
    b = ["a", "d", "e"]
    c = ["1", "2", "3"]
    
    # any element in `a` is a element of `b` ?
    any(map(lambda x:x in b, a))
    >>> True
    
    # any element in `a` is a element of `c` ?
    any(map(lambda x:x in c, a)) # any element in `a` is a element of `c` ?
    >>> False
    

    and high-order function

    has_any = lambda b: lambda a: any(map(lambda x:x in b, a))
    
    # using ...
    f1 = has_any( [1,2,3,] )
    f1( [3,4,5,] )
    >>> True
    f1( [6,7,8,] )
    >>> False
    
    0 讨论(0)
提交回复
热议问题