检查条件是否适用于列表中任何元素的 Pythonic 方法

2024-04-09

我有一个 Python 列表,我想检查是否有任何元素为负数。是否有一个简单的函数或语法可以用来对所有元素应用“是否为负”检查,并查看其中是否有任何元素为负?我浏览了文档 http://docs.python.org/library/stdtypes.html#typesseq-mutable并且找不到类似的东西。我能想到的最好的办法是:

if (True in [t < 0 for t in x]):
    # do something

我觉得这很不优雅。在 Python 中是否有更好的方法来做到这一点?


See also How to check if all elements of a list match a condition? https://stackoverflow.com/questions/10666163/ for checking the condition for all elements. Keep in mind that "any" and "all" checks are related through De Morgan's law https://stackoverflow.com/questions/2168603/, just as "or" and "and" are related.

Existing answers here use the built-in function any to do the iteration. See How do Python's any and all functions work? https://stackoverflow.com/questions/19389490 for an explanation of any and its counterpart, all.

If the condition you want to check is "is found in another container", see How to check if one of the following items is in a list? https://stackoverflow.com/questions/740287 and its counterpart, How to check if all of the following items are in a list? https://stackoverflow.com/questions/3931541/. Using any and all will work, but more efficient solutions are possible.


any() http://docs.python.org/library/functions.html#any:

if any(t < 0 for t in x):
    # do something

另外,如果您要使用“True in ...”,请将其设为生成器表达式,这样它就不会占用 O(n) 内存:

if True in (t < 0 for t in x):
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

检查条件是否适用于列表中任何元素的 Pythonic 方法 的相关文章

随机推荐