在Python中将一组浮点数四舍五入为整数

16

我有一个数字列表,需要在继续使用该列表之前将其四舍五入为整数。 例如,源列表如下:

[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]

我该怎么做才能将这个列表中的所有数字四舍五入为整数并保存呢?

7个回答

24
只需使用列表推导式中的round函数即可对所有列表成员进行四舍五入操作:
myList = [round(x) for x in myList]

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

如果你想要以特定精度round,请使用round(x,n)


13

您可以使用内置函数round()和列表推导式:

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

你也可以使用内置函数map()

newlist = list(map(round, list))

我不建议使用list作为名称,因为你会遮蔽内置类型。


1
你确定第二个方法不需要列表转换吗? - muyustan
2
@muyustan:你说得对。在我写这个答案的时候,我主要使用的是Python 2,在那里map已经返回一个列表,但是没错,现在已经改变了。 - zondo

4

如果您想设置有效数字的数量,您可以这样做

new_list = list(map(lambda x: round(x,precision),old_list))

此外,如果您有一个列表的列表,您可以执行:
new_list = [list(map(lambda x: round(x,precision),old_l)) for old_l in old_list]

2

NumPy非常适合处理这样的数组。
只需要使用np.around(list)或者np.round(list)即可。


可能对其他阅读此主题的人有帮助:np.rint - dat

2

使用 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]

2
你可以使用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]

1

由于其他答案利用了Python2的map,它返回一个list,而Python3的map返回一个迭代器,因此更新此内容以适应Python3。您可以使用list函数消耗您的map对象:

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(map(round, l))
[25, 193, 282, 88, 80, 450, 306, 282, 88, 676, 986, 306, 282]

要针对特定的 n 使用以下方式使用 round 函数,您需要使用 functools.partial
from functools import partial

n = 3
n_round = partial(round, ndigits=3)

n_round(123.4678)
123.468

new_list = list(map(n_round, list_of_floats))


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接