python range() for循环中的最大值

Tos*_*iro -3 python loops range

如何指定范围函数中的最大值,使其在特定数字后恢复到开头?

IE:

for i in range(253, 2):
    print i

Would print 253, 254, 255, 0 , 1, 2  
Run Code Online (Sandbox Code Playgroud)

如果最大值为 255


编辑(阅读评论和答案后)

这应该有效吗?

if start < end:
    list = [ i for i in range(start, end + 1 ) ]
else:
    list = [ i % 256 for i in range(start, end + 256 + 1 ) ]
Run Code Online (Sandbox Code Playgroud)

回顾这一点,人们似乎喜欢复杂而不是简单。当可以通过简单的循环完成时,为什么要使用 itertools 和其他复杂的构造呢?

bou*_*472 5

您想使用模算术(或时钟算术)。https://en.wikipedia.org/wiki/Modular_arithmetic

如果你想打印253, 254, 255, 0, 1, ..., 252,可以使用下面的代码。

for i in range(0, 256):
    print((253+i)%256)
Run Code Online (Sandbox Code Playgroud)