且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如果在Python中大于x,则将浮点列表转换为最接近的整数

更新时间:2023-02-04 19:28:41

使用python 条件表达式:

[round(x) if x > 0.5 else x for x in lst] 

例如:

>>> [round(x) if x > 0.5 else x for x in lst] 
[54.0, 86.0, 0.3, 1.0, 1.0, 14.0, 0.2]

要准确地获得它,我们需要从round的输出构造一个int:

To get it exactly, we need to construct an int from the output of round:

>>> [int(round(x)) if x > 0.5 else x for x in lst] 
[54, 86, 0.3, 1, 1, 14, 0.2]