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

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

我在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中执行此操作?

I have a list in Python, and I want to check if any elements are negative. Specman has the has() method for lists which does:

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

Where it is a Specman keyword mapped to each element of the list in turn.

I find this rather elegant. I looked through the Python documentation and couldn’t find anything similar. The best I could come up with was:

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

I find this rather inelegant. Is there a better way to do this in Python?


回答 0

any()

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

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

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

any():

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

Also, if you’re going to use “True in …”, make it a generator expression so it doesn’t take O(n) memory:

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

回答 1

使用any()

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

Use any().

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

回答 2

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

Python has a built in any() function for exactly this purpose.