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

烈酒焚心 提交于 2020-02-05 11:15:50

问题


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

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]

expected outcome:

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

回答1:


use the python conditional expression:

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

e.g.:

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

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



回答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


来源:https://stackoverflow.com/questions/16986859/convert-a-list-of-floats-to-the-nearest-whole-number-if-greater-than-x-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!