简体   繁体   English

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

[英]Convert a list of floats to the nearest whole number if greater than x in Python

I'm new to Python and I did my research but didn't get far, hence the post for help. 我是Python的新手,我做了研究,但是还没走很远,因此请寻求帮助。

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. 我有一个浮点数列表,仅当元素大于0.50时才想四舍五入到最接近的整数。

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

expected outcome: 预期结果:

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

use the python conditional expression : 使用python 条件表达式

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

eg: 例如:

>>> [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]

To get it exactly, we need to construct an int from the output of round : 为了准确地得到它,我们需要从round的输出构造一个int

>>> [int(round(x)) if x > 0.5 else x for x in lst] 
[54, 86, 0.3, 1, 1, 14, 0.2]
lst = [54.12,86.22,0.30,0.90,0.80,14.33,0.20]
new_list = [int(round(n)) if n > 0.5 else n for n in lst]

Output: 输出:

In [12]: new_list
Out[12]: [54, 86, 0.3, 1, 1, 14, 0.2]
  • list is a built in object name and should not be reassigned list是一个内置的对象名称,不应重新分配

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM