Timothy Tai - 1 year ago 51

Python Question

I am wondering if I can iterate over a list of lists with another list in python:

let's say

`lst_a = [x,y,z]`

lst_b = [[a,b,c,d],[e,f,g,h],[i,j,k,l]]

where len(lst_a) = len(lst_b)

I am wondering how to get a new list like below:

`lst_c = [[x/a, x/b, x/c, x/d],[y/e, y/f, y/g, y/h],[z/i, z/j, z/k, z/l]]`

thanks a lot!

tim

Answer Source

You can use a nested list comprehension

```
>>> lst_a = [1,2,3]
>>> lst_b = [[1,2,3,4],[2,3,4,5],[3,4,5,6]]
>>> lst_c = [[i/b for b in j] for i,j in zip(lst_a, lst_b)]
>>> lst_c
[[1.0, 0.5, 0.3333333333333333, 0.25], [1.0, 0.6666666666666666, 0.5, 0.4], [1.0, 0.75, 0.6, 0.5]]
```