Calculate the sum of the difference between 2 lists in Python

3

I need a function compara_listas(lista1, lista2) that receives two random lists and computes the sum of the difference between the elements of them. However, if any element of lista2 is greater than lista1 , it will become negative, and it must be positive.

As for example:

(lista1 = [4.34, 0.05, 0.02, 12.81, 2.16, 0.0], lista2 = [3.96, 0.05, 0.02, 22.22, 3.41, 0.0]) 

For example, (12.81 - 22.22) and (2.16 - 3.41) would be negative. So I would need to multiply by -1 to make it positive. How to do this without changing the others?

    
asked by anonymous 10.02.2017 / 00:49

1 answer

6

In a line of code:

A = [4.34, 0.05, 0.02, 12.81, 2.16, 0.0]
B = [3.96, 0.05, 0.02, 22.22, 3.41, 0.0]

print(sum(abs(a - b) for a, b in zip(A, B)))

The result: 11.04

How does it work?

First, we use the native function sum , which returns the sum of the elements of the list passed by parameter. To generate this list - which is actually an iterator - we join the two lists into a tuple iterator containing their values through the native function zip :

>>> zip(A, B)
[(4.34, 3.96), (0.05, 0.05), ..., (0.0, 0.0)]

Then, we iterate over this list, subtracting between the values and calculating the absolute value of the result, so that negative values are positive:

>>> abs(a - b) for a, b in zip(A, B)
[0.3799999999999999, 0.0, 0.0, 9.409999999999998, 1.25, 0.0]

The sum of the values: 11.04 .

  

See the code working in Repl.it .

    
10.02.2017 / 01:10