gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:09:53 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com