Convert list or numpy array of single element to float in python

后端 未结 4 1709
我在风中等你
我在风中等你 2020-12-14 16:24

I have a function which can accept either a list or a numpy array.

In either case, the list/array has a single element (always). I just need to return a float.

4条回答
  •  一向
    一向 (楼主)
    2020-12-14 16:47

    I would simply use,

    np.asarray(input, dtype=np.float)[0]
    
    • If input is an ndarray of the right dtype, there is no overhead, since np.asarray does nothing in this case.
    • if input is a list, np.asarray makes sure the output is of the right type.

提交回复
热议问题