Python标准库定义了一个any()
函数,它能够检查可迭代对象中是否存在元素为真。如果可迭代对象为空,则返回False。
any()
函数只检查元素是否为True
。我想指定一个回调函数来判断元素是否符合条件,例如:
any([1, 2, 'joe'], lambda e: isinstance(e, int) and e > 0)
Python标准库定义了一个any()
函数,它能够检查可迭代对象中是否存在元素为真。如果可迭代对象为空,则返回False。
any()
函数只检查元素是否为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
[]
或 list()
包装起来,它就会使用生成器并按预期工作。 - Ian Hunterany函数在任意条件为真时返回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.
实际上,“any”函数的概念源自Lisp,或者说源自函数式编程方法。还有另一个与之相反的函数,名为all
>>> 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)的平方的生成器。它们还允许在“for”子句上使用“if”子句来过滤项目,因此在你的例子中,可以使用:any (e for e in [1, 2, 'joe'] if isinstance(e, int) and e > 0)
>>> 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
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)
any
和map
的组合,如果你真的想保留lambda符号,代码如下:any(map(lambda e: isinstance(e, int) and e > 0, [1, 2, 'joe']))
但最好使用生成器表达式,因为它不会两次构建整个列表。
筛选器可以起作用,而且它会返回匹配的元素
>>> filter(lambda e: isinstance(e, int) and e > 0, [1,2,'joe'])
[1, 2]
>>> any((lambda: isinstance(e, int))() for e in [1,2,'joe'])
True
>>> any((lambda: isinstance(e, int))() for e in ['joe'])
False
你只需要包装未命名的lambda,并确保在每次传递时调用它,通过追加()
来实现。
这里的优点是,在遇到第一个int时仍然可以利用短路来评估任何when的值。
any(map(lambda:..., [...]))
,但是使用生成器表达式更符合惯用语。 - Thomas Ahle