我是 Python 的新手,我做了我的研究但没有深入,因此发帖寻求帮助。
我有一个 float 列表,只有当元素大于 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 conditional expression :
[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]
为了准确地得到它,我们需要从 round
的输出构造一个 int
:
>>> [int(round(x)) if x > 0.5 else x for x in lst]
[54, 86, 0.3, 1, 1, 14, 0.2]
关于python - 如果在 Python 中大于 x,则将 float 列表转换为最接近的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16986859/