问题描述
我在Python中有一个列表,我想检查是否有任何负数. Specman具有用于列表的has()
方法,
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
};
it
是一个Specman关键字,依次映射到列表的每个元素.
Where it
is a Specman keyword mapped to each element of the list in turn.
我觉得这很优雅.我浏览了Python文档找不到类似的东西.我能想到的最好的是:
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
我觉得这很不雅致.在Python中有更好的方法吗?
I find this rather inelegant. Is there a better way to do this in Python?
推荐答案
if any(t < 0 for t in x):
# do something
此外,如果要使用"True in ...",请将其设为生成器表达式,这样就不会占用O(n)内存:
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):
这篇关于检查条件是否满足列表中任何元素的Python方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!