我是 Python 新手,我进行了研究,但没有走多远,因此发帖寻求帮助。
我有一个浮点数列表,只有当元素大于 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]
为了准确地得到它,我们需要int
从 的输出构造一个round
:
>>> [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]
输出:
In [12]: new_list
Out[12]: [54, 86, 0.3, 1, 1, 14, 0.2]