I have two lists in Python:
a = [1, 5, 5]
b = [2, 10, 8]
If 1 < 2
and 5 < 10
and 5 < 8
, that is, if each element of the list a
is less than its corresponding element of list b
, then the variable c
will be equal to 1
; if it won't 0
work
I've tried to do it using numpy.where
but then I can't find a function that says if the resulting vector is empty or not (an equivalent isempty
of matlab's)
This is what I have tried so far:
a = [10, 10, 10]
b = [1, 1, 1]
a = np.asarray(a)
b = np.asarray(b)
if np.where(abs(a) / 5 < abs(b)): residual_check = 1
else: residual_check = 0
print(residual_check)
How could I do it?
You can directly compare both arrays and use
numpy.any
to see if any comparison isTrue
ornumpy.all
if you want them all to beTrue
:You can also use standard Python via
any
/all
andzip
:If you want it to
c
be 0/1 and notTrue
/False
you just have to cast:If used, it will
all
returnTrue
(1) if all the elements ofa
are less than those corresponding tob
. If used, it willany
returnTrue
if at least one element is relative to its partner.You can use the numpy.less function to compare lists element by element, thus obtaining an array with logical values, and then check if all elements are true using the numpy.all function :
If you want to do with "pure" python without any library, an option is a code like the following:
The zip operator allows you to iterate through each list, returning one element of each list at a time on each iteration. If you prefer not to use zip because you find it confusing, it would be something like:
To get
1
o0
instead ofTrue
oFalse
, you could directly change the function, "cast" to integercheck the function
numpy.array_equal(array1, array2)
Retora
True
if they are the same....False
if they are not.