[英]How to divide list of lists by another list of lists in Python?
我有q = [[7,2,3],[4,5,6]]
和r=[[6,1,2],[3,4,5]]
。 我需要將q除以r中的相應元素。 (即[[7/6,2/1,3/2],[4/3,5/4,6/5]]
)
所需的輸出B = [[1.16,2,1.5],[1.33,1.25,1.2]]
碼:
B= [[float(j)/float(i) for j in q] for i in r]
。
但是,我不斷收到錯誤消息:TypeError:float()參數必須為字符串或數字。 我已從將來導入部門。 有什么建議么?
使用zip將子列表成對組合,然后再次使用它將相應的分子和分母組合在一起:
>>> q = [[7,2,3],[4,5,6]]
>>> r = [[6,1,2],[3,4,5]]
>>> [[n/d for n, d in zip(subq, subr)] for subq, subr in zip(q, r)]
[[1.1666666666666667, 2.0, 1.5], [1.3333333333333333, 1.25, 1.2]]
你可以做:
>>> out=[]
>>> for s1, s2 in zip(q, r):
... inner=[]
... for n, d in zip(s1, s2):
... inner.append(float(n)/d)
... out.append(inner)
...
>>> out
[[1.1666666666666667, 2.0, 1.5], [1.3333333333333333, 1.25, 1.2]]
或者,使用numpy:
>>> q=[[7.,2.,3.],[4.,5.,6.]]
>>> r=[[6.,1.,2.],[3.,4.,5.]]
>>> np.array(q)/np.array(r)
array([[ 1.16666667, 2. , 1.5 ],
[ 1.33333333, 1.25 , 1.2 ]])
或者,如果您具有int文字:
>>> q=[[7,2,3],[4,5,6]]
>>> r=[[6,1,2],[3,4,5]]
>>> np.array(q, dtype=float)/np.array(r)
array([[ 1.16666667, 2. , 1.5 ],
[ 1.33333333, 1.25 , 1.2 ]])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.