如果在Python中大于x,则将浮点列表转换为最接近的整数 [英] Convert a list of floats to the nearest whole number if greater than x in Python

查看:88
本文介绍了如果在Python中大于x,则将浮点列表转换为最接近的整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python的新手,我进行了研究,但没有走很远,因此请寻求帮助.

I'm new to Python and I did my research but didn't get far, hence the post for help.

我有一个浮点数列表,仅当元素大于0.50时,我才想四舍五入到最接近的整数.

I have a list of floats which I would like to round to the nearest whole number ONLY if the element is greater than 0.50.

list = [54.12,86.22,0.30,0.90,0.80,14.33,0.20]

预期结果:

list = [54,86,0.30,1,1,14,0.20]

推荐答案

使用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]

这篇关于如果在Python中大于x,则将浮点列表转换为最接近的整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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