python - 如果在 Python 中大于 x,则将 float 列表转换为最接近的整数

标签 python list math int converters

我是 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/

相关文章:

python - 如何处理一个 url 中的多个 View ?

arrays - Ruby——将嵌套散列转换为多维数组

python - 将列表转换为嵌套字典

c# - 结合两个整数来创建一个唯一的数字

c# - 如何计算单个点质量?

Python Pandas 三行数据帧的最小极限

python - 为什么嵌套的空生成器会提前退出而不会引发错误?

python - virtualenv v16.7.2 powershell 激活脚本 : "You must ' source' this script: PS> . .\ENV\Scripts\activate”错误

list - 如何在 flutter 中将字符串列表转换为字符串?

python - Python 中意想不到的复数