[英]Convert a list of floats to the nearest whole number if greater than x in Python
我是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]
為了准確地得到它,我們需要從round
的輸出構造一個int
:
>>> [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]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.