Reputation: 29
So for the following two lists:
A=[ [1,2,3,4], [2,4,6,8], [2,5,8,10], [10,20,40,50] ]
B=[2, 3, 4, 5]
A is a list of lists, and B is a list. I would like to divide the first element of each sub-list in A by the first element of B, and the second element of each sub-list in A by the second element of B, etc to produce a third list C:
C = [ [1/2, 2/3, 3/4, 4/5], [2/2, 4/3, 6/4, 8/5], [2/2, 5/3, 8/4, 10/5], [10/2 ,20/3, 40/4, 50/5] ]
I am aware that the zip() function can be used to divide each element of a list by elements of another list, but I have only seen examples of this being used when both lists have identical structures. My attempt was to use the following:
C = [ [(m/n) for m, n in zip(subm, subn)] for subm, subn in zip(A, B)]
But this returns an error, presumably because both A and B have different number of elements. May someone explain to me how I could modify the above line of code to get in order to correctly obtain C? Thank you.
Upvotes: 0
Views: 111
Reputation: 5939
Another option to do it without zip
is numpy
:
import numpy as np
A = np.array([[1,2,3,4], [2,4,6,8], [2,5,8,10], [10,20,40,50]])
B = np.array([2, 3, 4, 5])
>>> (A/B).tolist()
[[0.5, 0.6666666666666666, 0.75, 0.8],
[1.0, 1.3333333333333333, 1.5, 1.6],
[1.0, 1.6666666666666667, 2.0, 2.0],
[5.0, 6.666666666666667, 10.0, 10.0]]
Upvotes: 0
Reputation: 11228
since you need to divide the inner list element with B, so you need to zip the inner sublist with B and loop through the A
A=[ [1,2,3,4], [2,4,6,8], [2,5,8,10], [10,20,40,50] ]
B=[2, 3, 4, 5]
res = [[a/b for a,b in zip(i, B)] for i in A]
Upvotes: 1