0

我想写一个函数来接受一个数值参数x,这个参数可以是无大小的,比如说x = 1或大小,一个列表,元组或 ndarray,比如说x = np.array([1,2])。有没有一种很好的方法来编写处理这两种情况的代码?

作为一个具体的例子,假设目标是广播x到一个数组(预定义的形状xshape),如果x只是一个数字,如果x是一个形状错误的数组,则返回一个错误。

import numpy as np
import sys

if np.shape(np.atleast_1d(x)) == (1,):
    x = np.ones(xshape) * x
elif np.shape(x) != xshape:
    sys.exit("wrong shape for x")

上面的代码似乎工作,除了嵌套困难x = [[2]]。它似乎也违背了一些推荐的做法,例如try / except. 任何建议表示赞赏。

4

1 回答 1

0

做到这一点的一种方法是推迟到 numpy,它处理所有各种情况并隐藏你的复杂性。例如:

>>> import numpy as np
>>> xshape = (2,)
>>> np.ones(xshape) * 1
array([ 1.,  1.])
>>> np.ones(xshape) * [9, 8]
array([ 9.,  8.])
>>> np.ones(xshape) * [[9, 8]]
array([[ 9.,  8.]])
>>> # Wrong shape
>>> np.ones(xshape) * [[9, 8, 7]]
ValueError                                Traceback (most recent call last)
<ipython-input-28-dd8a3b87c22c> in <module>()
----> 1 np.ones(xshape) * [[9, 8, 7]]

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

另一种相关方法是x = np.aarray(x)在函数/脚本的开头使用。如果x已经是一个数组,则什么也不会发生,但如果x是一个标量或序列,则会创建一个适当形状的数组,然后您可以编写其余代码,知道它x是一个数组(如果x不能转换为数组将引发错误)。

于 2013-02-02T00:10:58.890 回答