[英]Multiply two multi-dimension lists
例如,
Price = [['1', '5'], ['4', '9']]
Quantity = [['50.00', '0'], ['10.00', '20.00']]
想要有
Revenue = [['50.00', '0'], ['40.00', '180.00']]
嘗試使用列表理解,但不知道它如何用於此二維列表。
您可以通過使用內置功能zip
來執行此操作,而無需任何模塊:
Revenue = []
for ps, qs in zip(Price, Quantity):
rs = []
for p, q in zip(ps, qs):
rs.append('%.2f' % (float(p) * float(q)))
Revenue.append(rs)
使用列表推導
>>> [ [str(float(p[0]) * float(q[0])), str(float(p[1]) * float(q[1]))] for p, q in
zip(price, quantity) ]
[['50.0', '0.0'], ['40.0', '180.0']]
不是最易讀的,但可能有一種襯紙可以做到這一點:
Revenue = [map(lambda (price,quantity) : str(float(price)*float(quantity)), zip(Price[i],Quantity[i])) for i in range(len(Price))]
如果您選擇以下兩種方式之一,那么用Numpy (或Pandas )編寫起來就很容易而且很明顯,那就是:
Revenue = Price*Quantity
在完整程序中:
import numpy as np
Price = np.array( [[1, 5], [4, 9]] )
Quantity = np.array( [[50.0, 0], [10.00, 20.00]] )
Revenue = Price*Quantity
# [[ 50. 0.]
# [ 40. 180.]]
請注意,這里我放棄了OP的字符串表示法。 我認為這是一個初學者的錯誤,並且他們希望數字成為數字,並計划比這種簡單的方法進行更多的計算。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.