Python:将float 1.0返回为int 1,但将float 1.5返回为float 1.5 [英] Python: return float 1.0 as int 1 but float 1.5 as float 1.5
本文介绍了Python:将float 1.0返回为int 1,但将float 1.5返回为float 1.5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Python中,有一种方法可以将 1.0
转换为整数 1
,而同一函数将忽略 1.5
并将其保留为 float
?
In Python is there a way to turn 1.0
into a integer 1
while the same function ignores 1.5
and leaves it as a float
?
现在, int()
会将 1.0
转换为 1
,但也会将 1.5
向下舍入到 1
,这不是我想要的.
Right now, int()
will turn 1.0
into 1
but it will also round 1.5
down to 1
, which is not what I want.
推荐答案
从上面的评论继续:
使用 is_integer()
:
文档 :
Example from the docs:
>>> (1.5).is_integer()
False
>>> (1.0).is_integer()
True
>>> (1.4142135623730951).is_integer()
False
>>> (-2.0).is_integer()
True
>>> (3.2).is_integer()
False
输入:
s = [1.5, 1.0, 2.5, 3.54, 1.0, 4.4, 2.0]
因此:
print([int(x) if x.is_integer() else x for x in s])
包装在函数中
def func(s):
return [int(x) if x.is_integer() else x for x in s]
print(func(s))
如果您不想导入任何
:
def func(s):
return [int(x) if x == int(x) else x for x in s]
print(func(s))
将 map()
与 lambda
函数和迭代的 s
:
print(list(map(lambda x: int(x) if x.is_integer() else x, s)))
OR
print(list(map(lambda x: int(x) if int(x) == x else x, s)))
输出:
[1.5, 1, 2.5, 3.54, 1, 4.4, 2]
这篇关于Python:将float 1.0返回为int 1,但将float 1.5返回为float 1.5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文