Skip to content Skip to sidebar Skip to footer

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. I have a list of floats which I would like to round to the nearest whole number ONLY if the el

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

Solution 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

Post a Comment for "Convert A List Of Floats To The Nearest Whole Number If Greater Than X In Python"