在列表中查找上一个和下一个元素的最佳方法

Best way to find previous and next elements in a list

根据给定的元素索引查找上一个和下一个元素的有效方法是什么?

list = [(100, 112), (100, 100), (200, 100), (200, 125), (240, 130), (240, 100), (272, 100)]
idx = 2 # for example
print('Next elements are', list[idx + 1:] )

正确输出

Next elements are [(200, 125), (240, 130), (240, 100), (272, 100)]

虽然这一行打印了错误的元素:

print ('Prev elements are', list[idx - 1:])

输出错误

[(100, 100), (200, 100), (200, 125), (240, 130), (240, 100), (272, 100)]

为什么会这样?这个我也试过了list[(idx-1)%len(list):]

如果你有这样的数组:

arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

和索引定义:

index = 4

之前的元素:

print(arr[:index])
> [0, 1, 2, 3]

之后的元素:

print(arr[index+1:])
> [5, 6, 7, 8, 9]

PS:如果你的索引在range(0, len(arr)-2)那么你会得到元素之后,否则你会得到[].

前面元素的正确表达式是

print ('Prev elements are', list[:idx])

另外,小记,不要将列表命名为list,因为list是Python中的保留名称,用作语言提供的名称list类型!