【发布时间】:2020-11-08 22:16:43
【问题描述】:
考虑我有以下 np 数组列表:
>>> l = []
>>> l.append(np.array([[1,2,3],[4,5,6]]))
>>> l.append(np.array([[7,8],[9,10]]))
>>> l.append(np.array([[7,8],[9,10],[11,12]]))
我想找到此列表中所有 numpy 数组的每个单独值的平方和。执行以下操作:
>>> np.sum(np.square(l))
给出以下错误:
ValueError: operands could not be broadcast together with shapes (2,3) (2,2)
我如何以更 Pythonic 或 numpythonic 的方式做到这一点?我是否必须手动遍历每个 numpy 数组以找到它们的 squres,然后手动求和,如下所示?
>>> np.sum(list(map(lambda i: np.sum(np.square(i)),l)))
944
PS:
以下列表
>>> l
[array([[1, 2, 3],
[4, 5, 6]]), array([[ 7, 8],
[ 9, 10]])]
我可以做到:
>>> np.sum(np.square(np.hstack(l)))
385
但是hstack() 的输入列表的维度似乎有一些限制,因为它在第一个列表上给出了类似的错误。
【问题讨论】: