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

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

问题描述

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

在任何一种情况下,列表/数组都有一个元素(总是).我只需要返回一个浮点数.

因此,例如,我可以收到:

list_ = [4]

或 numpy 数组:

array_ = array([4])

我应该回来

<代码> 4.0

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

TypeError: float() 参数必须是字符串或数字

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

基于 numpy 数组转换为 float 的成功,这让我采用了这种方法:

float(np.asarray(list_))

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

问题

但似乎这种方法有一个开销,首先将列表转换为一个 numpy 数组,然后再转换为浮点数.基本上:有没有更好的方法来做到这一点?

解决方案

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

<预><代码>>>>列表_ = [4]>>>列表_[0]4>>>array_ = np.array([4])>>>数组_[0]4

这将是一个 int 因为这是您首先插入的内容.如果您出于某种原因需要它是一个浮点数,您可以在其上调用 float() 然后:

<预><代码>>>>浮动(列表_[0])4.0

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.

So, e.g., I could receive:

list_ = [4]

or the numpy array:

array_ = array([4])

And I should return

 4.0

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

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

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.

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

float(np.asarray(list_))

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

Question

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?

解决方案

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

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天全站免登陆