2016-02-26 89 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]