简体   繁体   English

将两个多维列表相乘

[英]Multiply two multi-dimension lists

For example, 例如,

Price = [['1', '5'], ['4', '9']]

Quantity = [['50.00', '0'], ['10.00', '20.00']]

want to have 想要有

Revenue = [['50.00', '0'], ['40.00', '180.00']]

Tried using list comprehension, but don't know how it works for this two-dimension lists. 尝试使用列表理解,但不知道它如何用于此二维列表。

You can do so without any modules by using the built-in function zip : 您可以通过使用内置功能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)

Using list comprehensions 使用列表推导

>>> [ [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))]

This is easy and obvious to write in Numpy (or Pandas ) if either of these an option for you, then it's just: 如果您选择以下两种方式之一,那么用Numpy (或Pandas )编写起来就很容易而且很明显,那就是:

Revenue = Price*Quantity

In the full program: 在完整程序中:

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

Note, that here I abandoned the OP's string notation. 请注意,这里我放弃了OP的字符串表示法。 I assume that it's a beginner's mistake, and that they want numbers to be numbers, and plan on doing more calculations than this simple one. 我认为这是一个初学者的错误,并且他们希望数字成为数字,并计划比这种简单的方法进行更多的计算。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM