简体   繁体   中英

python range() in for loop maximum

How do I specify a maximum in the range function to that it reverts back to the beginning after a certain number?

ie:

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

Would print 253, 254, 255, 0 , 1, 2  

If the maximum was 255


Edit (after reading comments and answers)

This should work right?

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

Looking back at this, people seem to love complexity over simplicity. Why use itertools and other complicated constructs when it can be done with a simple loop?

You want to use modular arithmetic (or clock arithmetic). https://en.wikipedia.org/wiki/Modular_arithmetic

If you want to print 253, 254, 255, 0, 1, ..., 252 , you can use the following code.

for i in range(0, 256):
    print((253+i)%256)

If I understood well, it's not exactly a range issue.

Given 2 numbers min and max :

  • if min < max , you want the list of numbers between min and max
  • else you want the list from min to 255 and 0 to max

It's only pseudo-code, but it might be enough to get you started to solve your problem (using one or two range calls)

There is some issues with the way you specify the range. But you could do something like this:

max_val = 255
for i in range(253, max_val+2):
    print i%max_val

But since range is specified with the end value not included you would need to do range(253, (max_val+1)+2) if you want the 2 to be printed.

If you beforehand do not know if the range-end value will be more or less than the range-start you could do

start = 253
end = 2 # +1 if you want the 2 to be printed
for i in range(start, end+(start>end and max_val or 0)):
    print i%max_val

Split it into two ranges: range1 = range(start, highest+1) and range2 = range(end) . Then using itertools, you can:

for i in it.chain(range1, range2):

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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