与非浮动类型一起使用浮点数

2024-04-24 05:28:08 发布

您现在位置:Python中文网/ 问答频道 /正文

根据我的question from earlier today(这是一个非常好的答案,我感谢大家的洞察力),我已经extended that small class来处理我们通常对整数和浮点数执行的几乎所有操作。在

现在我不确定如何将所有的条目转换为float,而不使用list comprehensions。在

例如,现在我有以下内容:

def __float__(self):
    return operalist(float(i) for i in self)

但当我调用以下命令序列时:

^{pr2}$

我更希望看到的是,通过使用列表理解,我们可以得到什么:

>>> [float(i) for i in X]
[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]

如何添加一个__float__方法,因为它似乎不是列表的本机方法?除非这不是个好主意。在


Tags: 方法答案infromselfextended列表for
1条回答
网友
1楼 · 发布于 2024-04-24 05:28:08

很遗憾,你不能。我找不到任何确切的措辞,但是the documentation states

Called to implement the built-in functions complex(), int(), float() and round(). Should return a value of the appropriate type.

我读到,__float__()应该返回一个float,因为^{}

[r]eturn[s] a floating point number constructed from a number or string x.


相比之下,纽比也不这么做。相反,它有一个方法astype(<type>)到它的ndarray,该方法转换为特定的<type>
这向我证实,这确实不可能做到。在

相关问题 更多 >