python - 手动将数组输入到python函数中

标签 python arrays function numpy

我想手动将一个二维数组输入到 python 函数中。

例如:

x = numpy.zeroes(1,2)
x[0,0] = 2
x[0,1] = 4
def f(x):
    return x**2
f(x)

此函数返回一个包含元素 4 和 16 的数组。但是,我希望能够手动将二维元素输入到函数中,例如 f(2,4), f([2,4]) 但它们不起作用。

最佳答案

输入f(2, 4)的原因和f([2, 4])不起作用,因为对于前者,该函数仅接受一个参数,而对于后者,您将传入一个 Python 列表。

Numpy 数组具有更多功能。 Python 列表则不然。当您查看它们的类方法时,您可以看到差异:

>>> x = numpy.array([[2.0, 4.0]])
>>> dir(x)
['T', '__abs__', '__add__', '__and__', '__array__', '__array_finalize__', '__array_interface__', '__array_prepare__', '__array_priority__', '__array_struct__', '__array_wrap__', '__class__', '__contains__', '__copy__', '__deepcopy__', '__delattr__', '__delitem__', '__delslice__', '__div__', '__divmod__', '__doc__', '__eq__', '__float__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__hex__', '__iadd__', '__iand__', '__idiv__', '__ifloordiv__', '__ilshift__', '__imod__', '__imul__', '__index__', '__init__', '__int__', '__invert__', '__ior__', '__ipow__', '__irshift__', '__isub__', '__iter__', '__itruediv__', '__ixor__', '__le__', '__len__', '__long__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__setitem__', '__setslice__', '__setstate__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__xor__', 'all', 'any', 'argmax', 'argmin', 'argpartition', 'argsort', 'astype', 'base', 'byteswap', 'choose', 'clip', 'compress', 'conj', 'conjugate', 'copy', 'ctypes', 'cumprod', 'cumsum', 'data', 'diagonal', 'dot', 'dtype', 'dump', 'dumps', 'fill', 'flags', 'flat', 'flatten', 'getfield', 'imag', 'item', 'itemset', 'itemsize', 'max', 'mean', 'min', 'nbytes', 'ndim', 'newbyteorder', 'nonzero', 'partition', 'prod', 'ptp', 'put', 'ravel', 'real', 'repeat', 'reshape', 'resize', 'round', 'searchsorted', 'setfield', 'setflags', 'shape', 'size', 'sort', 'squeeze', 'std', 'strides', 'sum', 'swapaxes', 'take', 'tobytes', 'tofile', 'tolist', 'tostring', 'trace', 'transpose', 'var', 'view']
>>> x = [2.0, 4.0]
>>> dir(x)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

请注意,numpy 数组有一个 __pow__方法,但 Python 列表没有。这是special method允许您指定 Python 如何使用 **数组上的函数。因此,numpy数组可以被平方。

>>> x = [1, 2, 3]
>>> x**2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int'

有几种方法可以解决这个问题。您可以像 Headcrab 所说的那样传入 numpy 数组,也可以使您的函数更加复杂。我将解释如何创建一个适合所有三种情况的函数。

要处理所有这三种情况,您必须检查传入的数据类型是什么,并且必须接受多个参数。

def f(x, *args):
    if args:
        # If there are multiple arguments e.g. f(2, 4)
        return [x**2] + [n**2 for n in args]
    elif isinstance(x, list):
        # If a Python list is passed e.g. f([2, 4])
        return [n**2 for n in x]
    else:
        # If something else (probably numpy array) is passed e.g. f(numpy.array([2, 4]))
        return x**2

一些测试用例:

>>> f(1, 2)
[1, 4]
>>> f(2, 4)
[4, 16]
>>> f(3, 6)
[9, 36]

.

>>> f([1, 2])
[1, 4]
>>> f([2, 4])
[4, 16]
>>> f([3, 6])
[9, 36]

.

>>> f(numpy.array([1, 2]))
array([1, 4])
>>> f(numpy.arry([2, 4]))
array([ 4, 16])
>>> f(numpy.array([3, 6]))
array([ 9, 36])

关于python - 手动将数组输入到python函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37934038/

相关文章:

python - 在急切执行期间不支持 session 关键字参数。您通过了 : {'learning_rate' : 1e-05}

python - 拒绝连接到 Postgresql

python - elastic beanstalk 上的 wsgi 用户权限

java - 比较三个单独列表中的产品

arrays - 如何在 http header 中传递数组?

java - java中不等于

c++ - 如何格式化我的函数以调用模板类?

python - 如何使用 Flask 渲染绘图列表

c++ - 函数的复杂参数

Python:如何修复绘制的 "random"值函数调用是否一致?