简体   繁体   中英

Find indexes in between 2 indexes in cyclical list

I have a list, which is cyclical. I want to find the indexes, which are in between two defined indexes. The starting index should be included, the ending index not. Here are some examples

start_index = 5
end_index = 2
lst = [10,11,12,13,14,15,16,17,18,19]

output: [5,6,7,8,9,0,1]
start_index = 2
end_index = 6
lst = [10,11,12,13,14,15,16,17,18,19]

output: [2,3,4,5]

You can try this.

 def indexes(start,end,lst):
    l = len(lst)
    if start > end:
        return list(range(start,l))+list(range(0,end))
    else:
        return list(range(start,end))

indexes(5,2,lst)
# [5, 6, 7, 8, 9, 0, 1]

indexes(2,6,lst)
# [2, 3, 4, 5]

We can use modular arithmetic to keep it simple:

def indicies(start, end, array):
    length = len(array)

    if end < start:
        end += length

    return [index % length for index in range(start, end)]

lst = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

print(indicies(5, 2, lst))
print(indicies(2, 6, lst))

OUTPUT

> python3 test.py
[5, 6, 7, 8, 9, 0, 1]
[2, 3, 4, 5]
>
def indexes(lst, start_index, end_index): 
    if start_index < len(lst) and end_index < len(lst): 
        if start_index > end_index: 
            print(list(range(start_index, len(lst))) + list(range(0, end_index))) 
        else: 
            print(list(range(start_index, end_index))) 
    else: 
        print("index greater than size of list") 
lst = [10,11,12,13,14,15,16,17,18,19] 
start_index = 5 
end_index = 2 
indexes(lst, start_index, end_index) 
start_index = 2 
end_index = 6 
indexes(lst, start_index, end_index)
#output                                                                                                 
#[5, 6, 7, 8, 9, 0, 1]
#[2, 3, 4, 5]

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