Python中带回调的any()函数
Python的标准库里有一个叫做 any()
的函数,
这个函数会返回True,如果可迭代对象(比如列表、元组等)里面有任何一个元素是“真”的话。如果这个可迭代对象是空的,它就返回False。
它只检查元素是否为 True
。我想要的是能够指定一个回调函数,来判断一个元素是否符合条件,比如:
any([1, 2, 'joe'], lambda e: isinstance(e, int) and e > 0)
8 个回答
15
你应该使用“生成器表达式”——这是一种可以处理迭代器的语言结构,可以在一行中应用过滤和表达式:
比如 (i ** 2 for i in xrange(10))
这个就是一个生成器,用来计算前10个自然数(0到9)的平方。
它们还允许使用“if”条件来过滤“for”循环中的项,所以针对你的例子,你可以使用:
any (e for e in [1, 2, 'joe'] if isinstance(e, int) and e > 0)
22
any 函数在任何条件为真时都会返回 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.
这两个函数在正确使用时真的很厉害。
157
这样怎么样:
>>> 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