python 中的模块化加法
我想将数字 y 添加到 x,但让 x 环绕以保持在 0 到 48 之间。注意 y 可以为负数,但其幅度永远不会大于 48。有没有比以下更好的方法:
x = x + y
if x >= 48:
x = x - 48
elif x < 0:
x = x + 48
?
I want to add a number y to x, but have x wrap around to remain between zero and 48. Note y could be negative but will never have a magnitude greater than 48. Is there a better way of doing this than:
x = x + y
if x >= 48:
x = x - 48
elif x < 0:
x = x + 48
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
模运算符是你的朋友。
The modulo operator is your friend.
如果您正在进行模运算,则只需使用模运算符即可。
If you're doing modular arithmetic, you simply need to use the modulo operator.
不仅仅是
(x+ y)% 48
适合您。在此处查看有关模的更多信息。Wouldn't just
(x+ y)% 48
be suitable for you. See more on modulo here.您可以使用模运算符:
you can use the modulo operator:
您可以使用
它为任何数字提供正的
x
。You can just use
which will give you positive
x
for any numbers.(x + y) % 48
将 48 替换为您喜欢的任何内容。
(x + y) % 48
Replace 48 with whatever you please.
您还可以创建一个类来处理模算术,就像这里所做的那样:
http://anh.cs.luc.edu/331/code/mod_arith.py
http://anh.cs.luc.edu/331/code/mod.py
You could also make a class to handle modular arithmetic, like have been done here:
http://anh.cs.luc.edu/331/code/mod_arith.py
http://anh.cs.luc.edu/331/code/mod.py
除了模 n 的余数之外,您可能还需要除法的结果,因此这里有一个秒到年+天+等的转换器,它演示了 divmod 函数。当然,人们可以继续使用“lustrum”、“几十年”、“几十个”、“世纪”或“两周”等。 ;)
You may need the result of the division besides the remainder modulo n, so here's a seconds-to-year+days+etc translator which demonstrates the divmod function. Of course, one could go on to lustrum, decades, scores, century, or use fortnight or such. ;)