Multiply a list of lists by a list of lists
The list of concepts is extensive, but they can be confusing, especially for a self-described beginner.
This path is (almost) equivalent to Adem Oztas answer, except for keeping the nested list structure:
def func(L1,L2):
result=[]
for xi,x in enumerate(L1):
result.append([])
for yi,y in enumerate(x):
result[xi].append(y*L2[xi][yi])
return result
print(func())
The list comprehension version would look like this:
[[y*L2[xi][yi] for yi,y in enumerate(x)] for xi,x in enumerate(L1) ]
This keeps the nested structure of the input list:
[[0],[0],[12,800,0]]
Equivalent to Apero's answer:
[[a*b for a,b in zip(x,y)] for x,y in zip(lst1,lst2)]
... will be like this:
def func(L1,L2):
result=[]
for x,y in zip(L1,L2):
r = []
result.append(r)
for a,b in zip(x,y):
r.append(a*b)
return result
print(func())
Both of these other answers (using lists) are better than what I did above using loops, since this is exactly what lists were created for. But seeing that it's done differently can be helpful to understand.
source to share
List<List<Integer>> output = new ArrayList<List<Integer>>();
for(int i = 0;i<lis1.size();i++){
List<Integer> subOutPut = new ArrayList<Integer>();
for(int j = 0;j<lis1.get(i).size();j++){
subOutPut.add(lis1.get(i).get(j)*lis2.get(i).get(j));
}
output.add(subOutPut);
}
In java, you can achieve as above
Login: [[0], [0], [12, 8, 0]]
*[[0], [0], [12, 8, 0]]
Output: [[0], [0], [12, 800, 0]]
source to share