【发布时间】:2012-04-16 17:32:04
【问题描述】:
在 python 中,我希望从 1-dim 数组中逐行减去 2-dim 数组。
我知道如何使用“for”循环和索引来做到这一点,但我想使用 numpy 函数可能会更快。但是我没有找到办法。这是一个带有“for”循环的示例:
from numpy import *
x=array([[1,2,3,4,5],[6,7,8,9,10]])
y=array([20,10])
j=array([0, 1])
a=zeros([2,5])
for i in j :
... a[i]=y[i]-x[i]
这是一个不起作用的例子,用这个替换'for'循环:
a=y[j]-x[j,i]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: shape mismatch: objects cannot be broadcast to a single shape
你有什么建议吗?
【问题讨论】:
-
作为建议,我会避免创建一个名为
j的列表变量。从语法上讲,这没问题,但大多数程序员在循环中为计数器保留字母i,j,k,这可能会导致一些混乱。