【发布时间】:2020-05-13 21:49:03
【问题描述】:
我有一个数字列表,在继续使用该列表之前,我需要将其四舍五入。示例源列表:
[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]
如何保存这个所有数字都舍入为整数的列表?
【问题讨论】:
我有一个数字列表,在继续使用该列表之前,我需要将其四舍五入。示例源列表:
[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]
如何保存这个所有数字都舍入为整数的列表?
【问题讨论】:
只需对所有具有列表理解的列表成员使用round 函数:
myList = [round(x) for x in myList]
myList # [25, 193, 282, 88, 80, 450, 306, 282, 88, 676, 986, 306, 282]
如果您希望 round 具有一定的精度 n 使用 round(x,n):
【讨论】:
如果你要设置你可以做的有效位数
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]
【讨论】:
你可以使用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]
【讨论】:
NumPy 非常适合处理这样的数组。
只需 np.around(list) 或 np.round(list) 即可。
【讨论】:
为 python3 更新这个,因为其他答案利用 python2 的 map,它返回一个 list,其中 python3 的 map 返回一个迭代器。您可以让 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]
要以这种方式将round 用于特定的n,您需要使用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))
【讨论】: