在python中循环到5(或其他数字)

是否有一个内置的函数可以这样圆:

10 -> 10 12 -> 10 13 -> 15 14 -> 15 16 -> 15 18 -> 20 

我不知道Python中的标准函数,但这对我有用:

 def myround(x, base=5): return int(base * round(float(x)/base)) 

很容易看出为什么上述工作。 你想确保你的数字除以5是一个整数,正确舍入。 所以,我们首先要做的是( round(float(x)/5) ),然后我们除以5,我们也乘以5。 最后转换为int是因为round()在Python中返回一个浮点值。

我通过给它一个base参数,使得函数更通用,默认为5。

舍入为非整数值,如0.05:

 def myround(x, prec=2, base=.05): return round(base * round(float(x)/base),prec) 

我发现这很有用,因为我可以做一个search,并在我的代码中更换“round(”到“myround(”,而不必更改参数值。

这只是一个缩放的问题

 >>> a=[10,11,12,13,14,15,16,17,18,19,20] >>> for b in a: ... int(round(b/5.0)*5.0) ... 10 10 10 15 15 15 15 15 20 20 20 

删除“rest”将工作:

 rounded = int(val) - int(val) % 5 

如果该值是一个整数:

 rounded = val - val % 5 

作为一个function:

 def roundint(value, base=5): return int(value) - int(value) % int(base) 

round(x [,n]):将值四舍五入为10的最接近的倍数,以减去n。 所以如果n是负数

 def round5(x): return int(round(x*2, -1)) / 2 

由于10 = 5 * 2,所以可以使用整数除法和乘法2,而不是浮点除法和乘法5.0。 不是那么重要,除非你喜欢转移

 def round5(x): return int(round(x << 1, -1)) >> 1 

修改版divround 🙂

 def divround(value, step, barrage): result, rest = divmod(value, step) return result*step if rest < barrage else (result+1)*step 

对不起,我想对Alok Singhai的回答发表评论,但不会因为缺乏声誉= /

无论如何,我们可以总结一下,走一步:

 def myround(x, base=5): return base * round(float(x) / base) 

这使我们可以使用非整数的基数,如.25或任何其他分数基数。

我意识到我迟到了,但似乎没有提到这个解决scheme:

 >>> from __future__ import division # This is only needed on Python 2 >>> def round_to_nearest(n, m): r = n % m return n + m - r if r + r >= m else n - r ... 

它不使用乘法,也不会从/转换为浮点数。

舍入到最接近的10的倍数:

 >>> for n in range(-21, 30, 3): print('{:3d} => {:3d}'.format(n, round_to_nearest(n, 10))) -21 => -20 -18 => -20 -15 => -10 -12 => -10 -9 => -10 -6 => -10 -3 => 0 0 => 0 3 => 0 6 => 10 9 => 10 12 => 10 15 => 20 18 => 20 21 => 20 24 => 20 27 => 30 

正如你所看到的,它适用于负数和正数。 领带(例如-15和15)将始终向上四舍五入。

类似的例子,没有四舍五入的最接近的倍数,表明它也performance为一个不同的“基”的预期:

 >>> for n in range(-21, 30, 3): print('{:3d} => {:3d}'.format(n, round_to_nearest(n, 5))) -21 => -20 -18 => -20 -15 => -15 -12 => -10 -9 => -10 -6 => -5 -3 => -5 0 => 0 3 => 5 6 => 5 9 => 10 12 => 10 15 => 15 18 => 20 21 => 20 24 => 25 27 => 25 
 def round_to_next5(n): return n + (5 - n) % 5 

如果有人需要“金融四舍五入”(总是0.5回合):

 def myround(x, base=5): roundcontext = decimal.Context(rounding=decimal.ROUND_HALF_UP) decimal.setcontext(roundcontext) return int(base *float(decimal.Decimal(x/base).quantize(decimal.Decimal('0')))) 

根据文档其他舍入选项是:

ROUND_CEILING(朝向Infinity),
ROUND_DOWN(朝零),
ROUND_FLOOR(朝向-Infinity),
ROUND_HALF_DOWN(最接近零的关系),
ROUND_HALF_EVEN(最接近最接近偶数的关系),
ROUND_HALF_UP(距离零距离最近),或者
ROUND_UP(远离零)。
ROUND_05UP(如果在舍入到零后的最后一位数字将为0或5,则为零;否则为零)

默认情况下,Python使用ROUND_HALF_EVEN,因为它有一些统计上的优势(舍入的结果没有偏见)。

那这个呢:

  def divround(value, step): return divmod(value, step)[0] * step 

** 5的下一个倍数**

考虑51需要转换为55

  code here mark=51; r=100-mark; a=r%5; new_mark=mark+a; 

你可以“欺骗” int()四舍五入,而不是将你传递给int()的数加0.5