[英]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.