I have a nested list that looks something like this:
list1=[[42, 432, 34, 242], [32, 68, 72, 90], [46, 78, 22, 24]]
and a flat list that looks something like this:
list2=[2,4,2,6]
How do I divided each consecutive element in list1 by each consecutive element in list2 (e.g. 42/2, 432/4, 34/2, 242/6) to get an output like this:
result=[[21,108,17,40],[16,17,36,15],[23,19,11,4]]
I have tried doing this:
for (item1, item2) in zip(list1, list2): avg_list.append(item1/item2)
but since list1 is a nested list there was some error in the code.
Advertisement
Answer
Here is a possible solution:
list1 = [[42, 432, 34, 242], [32, 68, 72, 90], [46, 78, 22, 24]] list2 = [2,4,2,6] result = [[int(x / y) for x, y in zip(lst, list2)] for lst in list1]
This is the output:
[[21, 108, 17, 40], [16, 17, 36, 15], [23, 19, 11, 4]]