2016-02-26 91 views
0

我有一個數字列表,在繼續使用列表之前,需要將其整數轉換爲整數。示例源列表:將浮點數列表舍入爲Python中的整數

[25.0, 193.0, 281.75, 87.5, 80.5, 449.75, 306.25, 281.75, 87.5, 675.5,986.125, 306.25, 281.75] 

我會怎麼做,以挽救這個列表的所有四捨五入到整數的數字?

回答

5

只需使用round功能適用於所有列表成員列表理解:

myList = [round(x) for x in myList] 

myList # [25, 193, 282, 88, 80, 450, 306, 282, 88, 676, 986, 306, 282] 

如果你想round某些presicion n使用round(x,n)

1

使用map功能的另一種方法。

您可以設置多少位數到round

>>> floats = [25.0, 193.0, 281.75, 87.5, 80.5, 449.75, 306.25, 281.75, 87.5, 675.5,986.125, 306.25, 281.75] 
>>> rounded = map(round, floats) 
>>> print rounded 
[25.0, 193.0, 282.0, 88.0, 80.0, 450.0, 306.0, 282.0, 88.0, 676.0, 986.0, 306.0, 282.0] 
+1

'round'產生浮在Python 2.如果不是你的輸出看起來像'[25.0,193.0,...]'? (我假設你沒有使用Python 3,因爲'print'作爲語句不起作用,'map'返回一個迭代器而不是列表。) –

+0

已經修復! :-) –

4

你可以使用內置的功能round()與列表理解:

newlist = [round(x) for x in list] 

你可以使用內置的功能map()

newlist = map(round, list) 

我不會推薦list作爲名稱,但是,因爲您重寫了內置類型。

0

您可以使用python內置的round函數。

l = [25.0, 193.0, 281.75, 87.5, 80.5, 449.75, 306.25, 281.75, 87.5, 675.5,986.125, 306.25, 281.75] 

list = [round(x) for x in l] 

print(list) 

輸出是:

[25, 193, 282, 88, 80, 450, 306, 282, 88, 676, 986, 306, 282]