Ответ 1
Вы имеете в виду что-то вроде:
allTrue = all(somePredicate(elem) for elem in someIterable)
anyTrue = any(somePredicate(elem) for elem in someIterable)
довольно уверен, что есть распространенная идиома, но не могу найти ее с помощью Google.
Вот что я хочу сделать (в java):
// Applies the predicate to all elements of the iterable, and returns
// true if all evaluated to true, otherwise false
boolean allTrue = Iterables.all(someIterable, somePredicate);
Как это делается "pythonic" в python?
Также было бы здорово, если бы я мог получить ответ для этого:
// Returns true if any of the elements return true for the predicate
boolean anyTrue = Iterables.any(someIterable, somePredicate);
Вы имеете в виду что-то вроде:
allTrue = all(somePredicate(elem) for elem in someIterable)
anyTrue = any(somePredicate(elem) for elem in someIterable)
allTrue = all(map(predicate, iterable))
anyTrue = any(map(predicate, iterable))
Вот пример, который проверяет, содержит ли список все нули:
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
Альтернатива, которую вы также можете сделать:
all(v == 0 for v in x)
Вы можете использовать встроенные функции "все" и "любые" в python
all(map(somePredicate, somIterable))
здесь somePredicate - это функция и 'all' будет проверять, является ли bool() этого элемента True