I am trying to subtract elements from a list in a list of lists using list comprehension. I want to achieve something like:
list1=[a,b,c] listoflist=[[e,f,g,h],[i,j],[k,l,m,n]] new_list= [[e-a,f-a,g-a,h-a],[i-b,j-b],[k-c,l-c,m-c,n-c]]
So it is an element to element subtraction but either get errors because most of my numbers are floats or I get something like:
new_list= [[[e,a],[f,b],[g,c]],[[i,a],[j,b]...]
I don’t know if that makes sense?
Advertisement
Answer
Here it is:
new_list = [[v1 - v2 for v1 in vs1] for v2, vs1 in zip(list1, listoflists)]