我有一个数字列表,需要在继续使用该列表之前将其四舍五入为整数。 例如,源列表如下:
[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
,请使用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]
NumPy非常适合处理这样的数组。
只需要使用np.around(list)
或者np.round(list)
即可。
np.rint
- datround
函数。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]
由于其他答案利用了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))
map
已经返回一个列表,但是没错,现在已经改变了。 - zondo