在Python中检查可迭代对象的所有元素是否满足条件
我很确定有一个常用的说法,但我在谷歌搜索中找不到...
我想在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);
在Python中怎么用“Pythonic”的方式来实现这个呢?
另外,如果能同时得到这个问题的答案就太好了:
// Returns true if any of the elements return true for the predicate
boolean anyTrue = Iterables.any(someIterable, somePredicate);
4 个回答
3
这里有一个例子,用来检查一个列表里是否全是零:
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)
18
在编程中,有时候我们需要让程序在特定的条件下执行某些操作。这就像给程序设定了一些规则,只有当这些规则被满足时,程序才会继续进行。
比如说,如果你想让程序在用户输入一个正确的密码后才能进入系统,你就需要设置一个条件:只有当输入的密码和预设的密码一致时,程序才会允许用户进入。这种条件判断在编程中非常常见。
此外,程序还可以根据不同的情况执行不同的操作。这就像在生活中,我们会根据天气的变化决定穿什么衣服。如果天气冷,我们就穿厚衣服;如果天气热,我们就穿薄衣服。在编程中,我们也可以根据不同的输入或状态来决定程序的行为。
总之,条件判断和控制程序执行流程是编程中非常重要的部分,它们帮助我们让程序变得更加智能和灵活。
allTrue = all(map(predicate, iterable))
anyTrue = any(map(predicate, iterable))
114
你是说像这样的吗:
allTrue = all(somePredicate(elem) for elem in someIterable)
anyTrue = any(somePredicate(elem) for elem in someIterable)