Jan
Jan

Reputation: 57

Calulate the differences between each element of two lists

I would like to calculate the difference of each entry of a list from each element of another list. Considering two lists A and B

A = [1,2,3,4] B=[5,6,7]

a new list c should have 12 entries

C=[1-5,1-6,1-7,2-5,2-6,2-7,....,4-7]
C=[-4,-5,-6,-3,-4,-5,....,-3]

Of course this is possible with loops, but is there a faster and more efficient way? My lists A and B have the dimensions 8000 and 2500, and I have to do it about 150 times in a row. Thank you very much in advance!

Upvotes: 0

Views: 113

Answers (2)

Aaditya Ura
Aaditya Ura

Reputation: 12669

You can try in one line without importing any module :

print(list(map(lambda x:list(map(lambda y:(x-y),b)),a)))

output:

[[-4, -5, -6], [-3, -4, -5], [-2, -3, -4], [-1, -2, -3]]

or using list comprehension :

print([(i-j) for i in a for j in b])

output:

[-4, -5, -6, -3, -4, -5, -2, -3, -4, -1, -2, -3]

Upvotes: 0

BENY
BENY

Reputation: 323226

By using repeat and tile from numpy

import numpy as np

np.repeat(A,len(B))-np.tile(B,len(A))
Out[221]: array([-4, -5, -6, -3, -4, -5, -2, -3, -4, -1, -2, -3])

Upvotes: 1

Related Questions