检查谓词是否为Python中的iterable中的所有元素计算为true

Enn*_*oji 38 python

我很确定有一个常见的习惯用法,但我无法通过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);
Run Code Online (Sandbox Code Playgroud)

这在Python中如何完成"Pythonic"?

如果我能得到这个答案也会很棒:

// Returns true if any of the elements return true for the predicate
boolean anyTrue = Iterables.any(someIterable, somePredicate);
Run Code Online (Sandbox Code Playgroud)

eum*_*iro 76

你的意思是:

allTrue = all(somePredicate(elem) for elem in someIterable)
anyTrue = any(somePredicate(elem) for elem in someIterable)
Run Code Online (Sandbox Code Playgroud)

  • 这些形式还具有"短路"的优点:`all`将在第一个'False`事件中终止,而'any`将在第一个'True`事件中终止. (6认同)
  • 我是唯一一个认为这种常见手术难以接受的人吗? (4认同)

Don*_*ell 9

allTrue = all(map(predicate, iterable))
anyTrue = any(map(predicate, iterable))
Run Code Online (Sandbox Code Playgroud)

  • @Space_C0wb0y - 在Python 3中,map返回迭代器而不是列表,因此不再需要imap. (3认同)