Compare two element-by-element vectors

6

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 list b , then the variable c will be% 1 ; if it will not be worth 0 .

I tried to do it using numpy.where but then I can not find a function that says if the resulting vector is empty or not (an equivalent to isempty of matlab)

This is what I have tried for the moment:

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?

    
asked by Luca cadalo 25.07.2017 в 09:33
source

3 answers

2

If you want to do with "pure" python without any library, an option is a code like the following:

def elementos_a_menor_que_elementos_b(a, b):
    if len(a) != len(b):
        print('Las listas no tiene el mismo tamaño')
        return False

    for item_a, item_b in zip(a, b):
        if item_a > item_b:
            return False

    return True


a = [1, 5, 5]
b = [2, 10, 8]

elementos_a_menor_que_elementos_b(a, b)

The zip operator allows you to iterate through each list, returning one item from each list to the once in each iteration. If you prefer not to use zip to find it confusing it would be something like:

for i in range(len(a)):
    item_a = a[i]
    item_b = b[i]
    [...]

To get 1 or 0 instead of True or False , you could change the function directly, "cast" to whole

int(True) == 1
int(False) == 0
    
answered by 25.07.2017 / 10:27
source
5

You can directly compare both arrays and use numpy.any to see if any comparison is True or numpy.all if you want them all to be True :

import numpy as np

c = np.all(np.array(a) < np.array(b))
import numpy as np

c = np.any(np.array(a) < np.array(b))

You can also use standard Python using any / all and zip :

c = all(i < j for i, j in zip(a, b))
c = any(i < j for i, j in zip(a, b))

If you want c to be 0/1 and not True / False you should only do casting:

c = int(np.all(np.array(a) < np.array(b)))

Using all will return True (1) if all the elements of a are less than those corresponding to b . If you use any you will return True if at least one element is relative to your partner.

    
answered by 25.07.2017 в 10:30
3

You can use the numpy.less function to compare the element-by-element lists, thus obtaining an array with logical values, and then checking whether all the elements are true using the numpy.all :

>>> np.all(np.less([1,5,5],[2,10,4]))
False
>>> np.all(np.less([1,5,5],[2,10,6]))
True
    
answered by 25.07.2017 в 10:19