我不确定我是否完全理解了这个问题,但也许这样的事情会有所帮助?
def square(x):
if 'numpy' in str(type(x)):
return np.square(x)
else:
if isinstance(x, list):
return list(np.square(x))
if isinstance(x, int):
return int(np.square(x))
if isinstance(x, float):
return float(np.square(x))
我定义了一些测试用例:
np_array_one = np.array([3.4])
np_array_mult = np.array([3.4, 2, 6])
int_ = 5
list_int = [2, 4, 2.9]
float_ = float(5.3)
list_float = [float(4.5), float(9.1), float(7.5)]
examples = [np_array_one, np_array_mult, int_, list_int, float_, list_float]
所以我们可以看到函数的行为方式。
for case in examples:
print 'Input type: {}.'.format(type(case))
out = square(case)
print out
print 'Output type: {}'.format(type(out))
print '-----------------'
还有输出:
Input type: <type 'numpy.ndarray'>.
[ 11.56]
Output type: <type 'numpy.ndarray'>
-----------------
Input type: <type 'numpy.ndarray'>.
[ 11.56 4. 36. ]
Output type: <type 'numpy.ndarray'>
-----------------
Input type: <type 'int'>.
25
Output type: <type 'int'>
-----------------
Input type: <type 'list'>.
[4.0, 16.0, 8.4100000000000001]
Output type: <type 'list'>
-----------------
Input type: <type 'float'>.
28.09
Output type: <type 'float'>
-----------------
Input type: <type 'list'>.
[20.25, 82.809999999999988, 56.25]
Output type: <type 'list'>
-----------------
从测试用例来看,输入和输出总是相同的。但是,功能不是很干净。
我在 SO 使用了来自 question 的一些代码。