简体   繁体   中英

Pythonic way of checking if a condition holds for any element of a list

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?

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):

Use any() .

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM