Check if a predicate evaluates true for all elements in an iterable in Python

前端 未结 4 419
孤街浪徒
孤街浪徒 2021-02-01 01:19

I am pretty sure there is a common idiom, but I couldn\'t find it with Google Search...

Here is what I want to do (in Java):



        
相关标签:
4条回答
  • 2021-02-01 01:46
    allTrue = all(map(predicate, iterable))
    anyTrue = any(map(predicate, iterable))
    
    0 讨论(0)
  • 2021-02-01 01:48

    You can use 'all' and 'any' builtin functions in Python:

    all(map(somePredicate, somIterable))
    

    Here somePredicate is a function and all will check if bool() of that element is True.

    0 讨论(0)
  • Do you mean something like:

    allTrue = all(somePredicate(elem) for elem in someIterable)
    anyTrue = any(somePredicate(elem) for elem in someIterable)
    
    0 讨论(0)
  • 2021-02-01 02:11

    Here is an example that checks if a list contains all zeros:

    x = [0, 0, 0]
    all(map(lambda v: v==0, x))
    # Evaluates to True
    
    x = [0, 1, 0]
    all(map(lambda v: v==0, x))
    # Evaluates to False
    

    Alternative you can also do:

    all(v == 0 for v in x)
    
    0 讨论(0)
提交回复
热议问题