返回np.array乘法不均匀的结果并打印ValueError

时间:2015-09-22 02:44:20

标签: python r numpy

我想要的输出基本上是复制R处理不均匀向量的方式。下面,R继续完成操作并报告错误。

> x <- c(1,2,3)
> y <- c(4,5,6)
> xy <- x * y
> xy
[1]  4 10 18
> y <- c(4,5,6,7)
> xy <- x * y
Warning message:
In x * y : longer object length is not a multiple of shorter object length
> xy
[1]  4 10 18  7
> 

在Python中使用numpy它的工作方式相同,只是它抛出一个ValueError并停止。

xy = 0
x = [1,2,3]
y = [4,5,6,7]

In [21]: xy = np.array(x) * np.array(y)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-21-0fa98c7ea5af> in <module>()
----> 1 xy = np.array(x) * np.array(y)

ValueError: operands could not be broadcast together with shapes (3,) (4,) 

有没有办法接受错误并产生输出和ValueError,这样如果我创建了一个简单的add或multiply函数,它总会返回一个值而不会中断ValueError?

 def vector_multiply(v, w):
         return np.array(v) * np.array(w)

会返回

 array([ 4, 10, 18, 6]
 ValueError: operands could not be broadcast together with shapes (3,) (4,)

修改 基于评论的可能解决方案

def vector_multiply(v, w):
    ...:     while length(v) == length(w):
    ...:         try:
    ...:             outarray = np.array(v) + np.array(w)           
    ...:             break
    ...:         except ValueError:
    ...:             print("ValueError: operands could not be broadcast together with shapes")
    ...:             if len(v) > len(w):
    ...:                 vmod = v[0:len(v) - a]
    ...:                 output = np.array(vmod) * np.array(w)
    ...:             else:
    ...:                 wmod = v[0:len(w) - a]
    ...:                 output = np.array(wmod) * np.array(v)
    ...:     return output

1 个答案:

答案 0 :(得分:0)

此任务称为“异常处理&#39;”。你可以在Python中这样做:

def vector_multiply(v, w):
    try: 
        answer = np.array(v) * np.array(w)
    except ValueError:
        print "Warning: shapes didn't match"
        answer = #whatever you want instead
    return answer