检查条件是否满足列表中任何元素的Python方法


110

我在Python中有一个列表,我想检查是否有任何负数。Specman具有has()用于列表的方法,该方法可以:

x: list of uint;
if (x.has(it < 0)) {
    // do something
};

itSpecman关键字又在哪里映射到列表的每个元素。

我觉得这很优雅。我浏览了Python文档,找不到类似的东西。我能想到的最好的是:

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

我觉得这很不雅致。有没有更好的方法在Python中执行此操作?

Answers:


186

any()

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

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

if True in (t < 0 for t in x):

1
更正:如果要使用True in ...,请重新考虑并any改为使用。
阿兰·菲


10

正是出于这个目的,Python内置了any()函数。


仅2.5+。否则,您必须创建一个函数,可能使用ifilter和异常,或bool(set((x如果有cond,则x,如果有cond))))等。
格雷格·林德

1
无需执行复杂的ifilter事情,只需执行以下操作:def any(it):for el:if el:return True; 返回False
Rory 2012年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.