Python标准库定义了 any() 功能

如果峰值的任何元素是正确的,则返回true。如果峰值为空,请返回false。

它仅检查元素是否评估 True. 。我希望它能够为此指定回调以判断元素是否适合账单:

any([1, 2, 'joe'], lambda e: isinstance(e, int) and e > 0)
有帮助吗?

解决方案

怎么样:

>>> any(isinstance(e, int) and e > 0 for e in [1,2,'joe'])
True

它也可以使用 all() 当然:

>>> all(isinstance(e, int) and e > 0 for e in [1,2,'joe'])
False

其他提示

任何 当任何条件都是正确的时,功能将返回true。

>>> any(isinstance(e, int) and e > 0 for e in [0 ,0, 1])
True # Returns True because 1 is greater than 0.


>>> any(isinstance(e, int) and e > 0 for e in [0 ,0, 0])
False # Returns False because not a single condition is True.

实际上,的概念 任何 功能是从LISP带来的,或者您可以从功能编程方法中说。还有另一个功能与之相反 全部

>>> all(isinstance(e, int) and e > 0 for e in [1, 33, 22])
True # Returns True when all the condition satisfies.

>>> all(isinstance(e, int) and e > 0 for e in [1, 0, 1])
False # Returns False when a single condition fails.

正确使用时,这两个功能真的很酷。

您应该使用“生成器表达式” - 即,可以消耗迭代器并在一行上应用过滤器和表达式的语言构造:

例如 (i ** 2 for i in xrange(10)) 是前10个自然数(0至9)的平方的发电机

他们还允许“ if”子句过滤“ for”子句上的itens,因此,对于您的示例,您可以使用:

any (e for e in [1, 2, 'joe'] if isinstance(e, int) and e > 0)

Antoine P的答案略有改进

>>> any(type(e) is int for e in [1,2,'joe'])
True

为了 all()

>>> all(type(e) is int for e in [1,2,'joe'])
False

虽然其他人给出了很好的Pythonic答案(在大多数情况下我只是使用接受的答案),但我只是想指出,如果您真的更喜欢,那么自己做自己做这件事是多么容易:

def any_lambda(iterable, function):
  return any(function(i) for i in iterable)

In [1]: any_lambda([1, 2, 'joe'], lambda e: isinstance(e, int) and e > 0
Out[1]: True
In [2]: any_lambda([-1, '2', 'joe'], lambda e: isinstance(e, int) and e > 0)
Out[2]: False

我认为我至少会首先使用函数参数定义它,因为这会更匹配现有的内置功能,例如map()和filter():

def any_lambda(function, iterable):
  return any(function(i) for i in iterable)

过滤器可以正常工作,再返回您的匹配元素

>>> filter(lambda e: isinstance(e, int) and e > 0, [1,2,'joe'])
[1, 2]

您可以使用 anymap 如果您真的想保留这样的lambda符号:

any(map(lambda e: isinstance(e, int) and e > 0, [1, 2, 'joe']))

但是最好使用发电机表达式,因为它不会两次构建整个列表。

如果你 真的 想要在任何()中嵌入lambda,您可以这样做:

>>> any((lambda: isinstance(e, int))() for e in [1,2,'joe'])
True
>>> any((lambda: isinstance(e, int))() for e in ['joe'])
False

您只需要结束未命名的lambda,并通过附加 ()

这里的优点是,当您击中第一个INT时,您仍然可以利用短路的评估

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top