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
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]]
lst_a = [x,y,z]
lst_b = [[a,b,c,d],[e,f,g,h],[i,j,k,l]]
lst_c = []
for i in range(len(lst_a)):
lst_c.append([lst_a[i]/lst_b[i][0]])
for j in range(1, len(lst_b[i])):
lst_c[i].append(lst_a[i]/lst_b[i][j])
You can do this using numpy.
import numpy
lst_a = [x,y,z]
lst_b = [[a,b,c,d],[e,f,g,h],[i,j,k,l]]
new_list = []
for i, item in enumerate(lst_a):
new_list_i = float(lst_a[i])/numpy.array(lst_b[i])
new_list.append(new_list_i.tolist())
print new_list
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.