简体   繁体   English

如何在 python 中四舍五入?

[英]how do I round by n groups in python?

I am working on a way to create anonymus data.我正在研究一种创建匿名数据的方法。 Therefore I want to to some sort of rounding my data.因此,我想对我的数据进行某种舍入。 But this should happen in n-groups that have the same range.但这应该发生在具有相同范围的 n 组中。 minimal group should be min(a) and from there on it goes in n steps to max(a)-diff(max(a),min(a))/n最小组应该是 min(a) 并从那里开始 n 步到 max(a)-diff(max(a),min(a))/n

example 1:示例 1:

a = [10,11,14,15,16.5,17,19]
round_n_groups(x=a,n_groups=5)

returns:
[10,10,14,14,16,16,18]

example 2:示例 2:

b = [-.5,.1,.7,1.3]
round_n_groups(x=b,n_groups=2)

returns:
[-.5,-.5,.4,.4]

I would go naivey with 2 for loops.我会 go 天真地使用 2 个 for 循环。 One that creates the group of possible values with your formula "max(a)-diff(max(a),min(a))/n", and then I would loop through your input x and attribute the closed value it finds in the group of possible values..一个使用您的公式“max(a)-diff(max(a),min(a))/n”创建一组可能值的方法,然后我将遍历您的输入 x 并将其找到的闭合值归因于一组可能的值..

Here's how the round function works:以下是圆形 function 的工作原理:

x = 2.5
y = round(x,1)
z = round(x,2)
print(y)
print(z)

Hope this helps you understand.希望这可以帮助您理解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM