Rounding a list of floats into integers in Python

百般思念 提交于 2020-03-18 04:56:25

问题


I have a list of numbers which I need to round into integers before I continue using the list. Example source list:

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

What would I do to save this list with all of the numbers rounded to an integer?


回答1:


Simply use round function for all list members with list comprehension :

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

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

If you want round with certain presicion n use round(x,n):




回答2:


You could use the built-in function round() with list comprehension:

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

You could use the built-in function map():

newlist = map(round, list)

I wouldn't recommend list as a name, though, because you are overriding the built-in type.




回答3:


You can use python's built in round function.

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)

The output is:

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



回答4:


Another approach using map function.

You can set how many digits to 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]



回答5:


NumPy is great for handling arrays like this.
Simply np.around(list) or np.round(list) works.




回答6:


Updating this for python3 since other answers leverage python2's map, which returns a list, where python3's map returns an iterator. You can have the list function consume your map object:

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]

To use round in this way for a specific n, you'll want to use 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))



来源:https://stackoverflow.com/questions/35651470/rounding-a-list-of-floats-into-integers-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!