我有一个列表,它是循环的。我想找到位于两个定义的索引之间的索引。起始索引应该被包括在内,而结束索引不包括在内。下面是一些例子
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]
我们可以使用模块运算来保持简单。
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(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]
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]