[英]Multiplication of list of lists with list of lists
V = [[10,20],[40,50]]
I = [[1,2],[4,5]]
print(V*I)
** output is:TypeError: can't multiply sequence by non-int of type 'list' **输出为:TypeError:无法将序列乘以'list'类型的非整数
**I want the output something like V*I = [[10,40],[160,250]] **我希望输出类似V * I = [[10,40],[160,250]]
[[x * y for x, y in zip(i, v)] for i, v in zip(I, V)]
most general and most pythonic. [[x * y for x, y in zip(i, v)] for i, v in zip(I, V)]
,这是最通用和最pythonic的。
Specifically for nested lists of 2 elements: 专门用于2个元素的嵌套列表:
[[x1 * x2, y1 * y2] for (x1, y1), (x2, y2) in zip(V, I)]
More generally, for nested lists of any length: 更一般而言,对于任何长度的嵌套列表:
[[x * y for x, y in zip(i, v)] for i, v in zip(I, V)]
Nested lists where all the inner lists have the same number of elements: 嵌套列表,其中所有内部列表具有相同数量的元素:
(np.array(I) * np.array(V)).tolist()
Nested lists when inner lists might have different number of elements but corresponding lists have same number of elements: 当内部列表可能具有不同数量的元素但相应列表具有相同数量的元素时的嵌套列表:
[(np.array(i) * np.array(v)).tolist() for i, v in zip(I, V)]
The last one is pretty ugly but numpy
is not designed to handle matrix with different number of columns. 最后一个很丑陋,但是numpy
并非旨在处理具有不同列数的矩阵。
Using zip
and list comprehension. 使用zip
和列表理解。
Ex: 例如:
V = [[10,20],[40,50]]
I = [[1,2],[4,5]]
res = []
for i in zip(V, I):
res.append([j * k for j, k in zip(*i)])
print(res)
Output: 输出:
[[10, 40], [160, 250]]
当然不是最佳工具,但是在普通的Python中,这种嵌套的理解将适用于2D矩阵:
[[a*b for a, b in zip(v, i)] for v, i in zip(V, I)]
>>> [[x*y for x,y in zip(*t)] for t in zip(V, I)]
[[10, 40], [160, 250]]
Use numpy
: 使用numpy
:
import numpy as np
V = np.matrix([[10,20],[40,50]])
I = np.matrix([[1,2],[4,5]])
np.multiply(V,I)
Gives: 给出:
[[ 10 40]
[160 250]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.