job.answiz.com
  • 1
Votes
name
name Punditsdkoslkdosdkoskdo

When a function which has one parameter receives np.array

Suppose there is a function:

def test(x):
    return x**2

When I give a list of ints to the function, an error is raised:

TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int'

But an array of ints instead, the function returns an array of outputs.

How is this possible?

 

You can use the numpy.asarray function to convert any sequence-like input to an array:

>>> import numpy
>>> numpy.asarray([1,2,3])
array([1, 2, 3])
>>> numpy.asarray(numpy.array([2,3]))
array([2, 3])
>>> numpy.asarray(1)
array(1)
>>> numpy.asarray((2,3))
array([2, 3])
>>> numpy.asarray({1:3,2:4})
array({1: 3, 2: 4}, dtype=object)

Another Method :you this  function that will except *args as an array also:

>>> def f(*args):
...    args = numpy.asarray(args[0]) if len(args) == 1 else numpy.asarray(args)
...    return args
... 
>>> f(7,3,5)
array([7, 3, 5])
>>> f([1,2,3])
array([1, 2, 3])
>>> f((2,3,4))
array([2, 3, 4])
>>> f(numpy.array([1,2,3]))
array([1, 2, 3])
  • 0
Reply Report


Related Questions

Trending Tags