问题
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