[英]Rounding a list of floats into integers in Python
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?我该怎么做才能保存所有数字四舍五入为整数的列表?
Simply use round
function for all list members with list comprehension :只需对具有列表理解的所有列表成员使用
round
函数:
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)
:如果你想
round
某些presicion n
使用round(x,n)
You could use the built-in function round()
with a list comprehension:您可以将内置函数
round()
与列表理解一起使用:
newlist = [round(x) for x in list]
You could also use the built-in function map()
:您还可以使用内置函数
map()
:
newlist = list(map(round, list))
I wouldn't recommend list
as a name, though, because you are shadowing the built-in type.不过,我不建议将
list
作为名称,因为您正在隐藏内置类型。
If you would set the number of significant digits you could do如果你想设置你可以做的有效数字的数量
new_list = list(map(lambda x: round(x,precision),old_list))
Furthermore, if you had a list of list you could do此外,如果你有一个列表列表,你可以做
new_list = [list(map(lambda x: round(x,precision),old_l)) for old_l in old_list]
Another approach using map
function.另一种使用
map
功能的方法。
You can set how many digits to round
.您可以设置要
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]
You can use python's built in round
function.您可以使用 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)
The output is:输出是:
[25, 193, 282, 88, 80, 450, 306, 282, 88, 676, 986, 306, 282]
NumPy is great for handling arrays like this. NumPy 非常适合处理这样的数组。
Simply np.around(list)
or np.round(list)
works.只需
np.around(list)
或np.round(list)
。
Updating this for python3 since other answers leverage python2's map
, which returns a list
, where python3's map
returns an iterator.为 python3 更新这个,因为其他答案利用 python2 的
map
,它返回一个list
,其中 python3 的map
返回一个迭代器。 You can have the list
function consume your map
object:您可以让
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]
To use round
in this way for a specific n
, you'll want to use functools.partial
:要以这种方式对特定
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.