问题描述
如果我想检查列表中的所有元素
If I want to like to check if all the elements in a list
a:[1 2 3 6]
大于或等于另一个列表中的相应元素
are greater than or equal to their corresponding elements in another list
b:[0 2 3 5]
如果所有 i 都为a [i]> b [i],则返回true,否则返回false.有逻辑功能吗?例如a> b?谢谢
If a[ i ] > b[ i ] for all i's, then return true, otherwise false.Is there a logical function for this? such as a>b? Thanks
推荐答案
如果您实际上想将 a
中的每个元素与 b
进行比较,则实际上只需要进行检查即可 b
的 max
,因此,如果我们发现小于b的最大值的元素,它将是 0(n)
解决方案短路./p>
If you actually want to compare every element in a
against b
you actually just need to check against the max
of b
so it will be an 0(n)
solution short circuiting if we find any element less than the max of b:
mx = max(b)
print(all(x >= mx for x in a))
对于成对,您可以使用枚举:
For pairwise you can use enumerate:
print(all(x >= b[ind] for ind,x in enumerate(a)))
或者使用hughbothwell的zip想法,请使用itertools.zip:
Or using hughbothwell's zip idea use itertools.zip:
from itertools import izip
print(all(x >= y for x,y in izip(a,b)))
或者numpy:
print(np.greater_equal(a,b).all())
print(np.all(a >= b))
这篇关于Python:两个列表之间的成对比较:列表a> =列表b?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!