将单个元素的列表或numpy数组转换为浮在python中 [英] Convert list or numpy array of single element to float in python

查看:77
本文介绍了将单个元素的列表或numpy数组转换为浮在python中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可以接受列表或numpy数组的函数.

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.

例如,我可以收到:

list_ = [4]

或numpy数组:

array_ = array([4])

我应该回来

 4.0

因此,自然地(我会说),我在list_上使用float(...)并得到:

So, naturally (I would say), I employ float(...) on list_ and get:

TypeError: float() argument must be a string or a number

我对array_做相同的操作,这次它通过响应"4.0"来工作.由此,我了解到Python的列表无法以这种方式转换为浮点数.

I do the same to array_ and this time it works by responding with "4.0". From this, I learn that Python's list cannot be converted to float this way.

基于成功进行numpy数组转换以使其浮动的方法,我将这种方法带入了方法:

Based on the success with the numpy array conversion to float this lead me to the approach:

float(np.asarray(list_))

当list_既是Python列表又是numpy数组时,此方法有效.

And this works when list_ is both a Python list and when it is a numpy array.

问题

但是这种方法似乎有开销,首先需要将列表转换为numpy数组,然后再进行浮点运算.基本上:有更好的方法吗?

But it seems like this approach has an overhead first converting the list to a numpy array and then to float. Basically: Is there a better way of doing this?

推荐答案

仅使用索引访问和索引0访问列表/数组的第一项:

Just access the first item of the list/array, using the index access and the index 0:

>>> list_ = [4]
>>> list_[0]
4
>>> array_ = np.array([4])
>>> array_[0]
4

这将是一个int,因为这是您首先插入的内容.如果出于某种原因需要将其作为浮动对象,则可以在其上调用float()

This will be an int since that was what you inserted in the first place. If you need it to be a float for some reason, you can call float() on it then:

>>> float(list_[0])
4.0

这篇关于将单个元素的列表或numpy数组转换为浮在python中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆