[英]iterate over a list of lists with another list in python
我想知道是否可以在python中使用另一個列表遍歷列表列表:
比方說
lst_a = [x,y,z]
lst_b = [[a,b,c,d],[e,f,g,h],[i,j,k,l]]
其中len(lst_a)= len(lst_b)
我想知道如何獲得如下所示的新列表:
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]]
非常感謝!
蒂姆
您可以使用嵌套列表理解
>>> 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])
您可以使用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.