The sum of the difference between 2 Python lists

Asked

Viewed 2,187 times

3

I need a function compara_listas(lista1, lista2) which receives two random lists and calculates the sum of the difference between their elements. But if any element of the lista2 is greater than the lista1, it’s going to be negative, and it needs to be positive.

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 the (12.81 - 22.22) and the (2.16 - 3.41) would be negative. Then I would need to multiply by -1 to make it positive. How to do this without changing the others?

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 it works?

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

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

After, we iterate on 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 on Repl.it.

  • Apparently solved the problem. Thanks for your help!

  • 2

    People, be like @Anderson and explain what they’re doing when they answer the questions. Especially on one Liners. : -) +1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.