Difference function

Is there a function in Python to get the difference between two or more values ​​in a list? So, in these two lists:

list1 = [1, 5, 3, 7] list2 = [4, 2, 6, 4] 

I need to calculate the difference between each value in list1 and list2.

 for i in list1: for ii in list2: print i -ii 

This gives negative values, but I want to subtract between the values ​​of these two lists only from the highest value to the lowest value to get negative values.

In the above lists, I expect the output to be [3, 3, 3, 3] .

Thanks.

+5
source share
5 answers

You can also fulfill the if else condition inside the list comprehension.

 >>> [ij if i>j else ji for i,j in zip(list1, list2)] [3, 3, 3, 3] 
+6
source

Assuming you expect [3, 3, 3, 3] as an answer in your question, you can use abs and zip :

 [abs(ij) for i,j in zip(list1, list2)] 
+10
source

Either zip lists, or use numpy :

 >>> list1 = [1, 5, 3, 7] >>> list2 = [4, 2, 6, 4] >>> [ab for a,b in zip(list1, list2)] [-3, 3, -3, 3] >>> import numpy as np >>> np.array(list1) - np.array(list2) array([-3, 3, -3, 3]) 

Remember to return the array to the list as needed.

change

In response to the new requirement that absolute values ​​are needed: you can add abs to the list comprehension:

 >>> [abs(ab) for a,b in zip(list1, list2)] [3, 3, 3, 3] 

and the numpy solution would change to:

 >>> map(abs, np.array(list1) - np.array(list2)) [3, 3, 3, 3] 
+8
source

You can use the zip method to combine these two lists. See zip tutorials https://docs.python.org/2/library/functions.html#zip

 >>> list1 = [1, 5, 3, 7] >>> list2 = [4, 2, 6, 4] >>> [abs(xy) for x, y in zip(list1, list2)] [3, 3, 3, 3] 
+2
source

Avinash Raj's answer is correct, or alternatively with map ():

 from operator import sub C = map(sub, A, B) 
+1
source

Source: https://habr.com/ru/post/1239319/


All Articles