带有回调的 Python 中的 any() 函数 [英] any() function in Python with a callback

查看:37
本文介绍了带有回调的 Python 中的 any() 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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'])真的

它当然也适用于 all():

<预><代码>>>>all(isinstance(e, int) and e > 0 for e in [1,2,'joe'])错误的

The Python standard library defines an any() function that

Return True if any element of the iterable is true. If the iterable is empty, return False.

It checks only if the elements evaluate to True. What I want it to be able so specify a callback to tell if an element fits the bill like:

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

解决方案

How about:

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

It also works with all() of course:

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

这篇关于带有回调的 Python 中的 any() 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆