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]
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
You could just do
all(x >= y for x,y in zip(a,b))
which has the advantage of short-circuit evaluation: if it finds any x < y
it returns False
immediately.
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)))
Or using hughbothwell's zip idea use itertools.zip:
from itertools import izip
print(all(x >= y for x,y in izip(a,b)))
Or numpy:
print(np.greater_equal(a,b).all())
print(np.all(a >= b))
You can write out an explicit for loop, or you can do an inline double loop and an all as shown below with the interpreter.
>>> a = {1,2,3,4}
>>> b = {2,3,4,5}
>>> lst = [x>y for x in a for y in b]
>>> lst
[False, False, False, False, False, False, False, False, True, False, False, False, True, True, False,False]
>>> all(bool==True for bool in lst)
False
If you are willing to use numpy, you can do this with a logic function (and it's much faster than pure python list comparisons)
>>> from numpy import array
>>> a=array([1,2,3,4,5])
>>> b=array([3,0,3,1,2])
>>> a > b
array([False, True, False, True, True], dtype=bool)
>>>
How about this? Do I win the code-golf?
a=[1,3,8,6]
b=[0,2,3,5]
print all(map(cmp,a,b))
a = [1, 2, 3, 6]
b = [0, 2, 3, 5]
def check_lists(a, b):
result = []
for i in range(len(a)):
result.append(a[i] >= b[i])
return result
print check_lists(a, b)
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.