简体   繁体   中英

Python, loop through list within a range

I have a list with the values 0 to 30.

How can I loop through these values (within a range) with an added offset?

As that might not make any sense, I've made a little diagram:

图

This handles the wrap-around case

def list_range(offset, length, l):
    # this handles both negative offsets and offsets larger than list length
    start = offset % len(l)
    end = (start + length) % len(l)
    if end > start:
        return l[start:end]
    return l[start:] + l[:end]

Edit: We now handle the negative index case.

Edit 2: Example usage in interactive shell.

>>> l = range(30)
>>> list_range(15,10,l)
[15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
>>> list_range(25,10,l) # I'm guessing the 35 in the example was accidental
[25, 26, 27, 28, 29, 0, 1, 2, 3, 4]
>>> list_range(-8,10,l)
[12, 13, 14, 15, 16, 17, 18, 19, 20, 21]

Edit 3: updated to ignore the -8,10 case per comments

Edit 4: I'm using list slices because I suspect they are more efficient than looping over the data. I just tested that out and my hunch was correct, it is about 2x faster than mVChr's version which loops over the list. However, that may be a premature optimisation and the more pythonic answer(list comprehension one-liner) may be better in your case

This will work for all cases except your last one with the negative offset:

[(i + offset) % max_range for i in xrange(count)]

# e.g.
max_range = 30
count = 10
offset = 15
print [(i + offset) % max_range for i in xrange(count)]
# [15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
offset = 25
print [(i + offset) % max_range for i in xrange(count)]
# [25, 26, 27, 28, 29, 0, 1, 2, 3, 4]

That should get you on the right track, though I'm unsure how best to handle the last case.

Couldn't you just say

List = range(30)
newList = []
for i in range(n):
    newList.append(List[n+offset])

This isn't super general, but should work for the cases listed in your example file.

def loopy(items, offset, num):
    for i in xrange(num):
        yield items[(offset + i) % len(items)]


>>> x = range(30)
>>> print list(loopy(x, 25, 10))
[25, 26, 27, 28, 29, 0, 1, 2, 3, 4]

ok so lets say you have a list, to get your new list

list=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
newlist=[]
#let's say I want 5 through 10
for n in range(5,11):
   newlist.append(list[n])

The newlist will be 5 through 10. For doing numbers that loop around use negatives, so like range(-1,4) will give you 15,0,1,2,3,4

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