Pythonic Circular List

前端 未结 7 1933
闹比i
闹比i 2020-12-03 01:10

Say I have a list,

l = [1, 2, 3, 4, 5, 6, 7, 8]

I want to grab the index of an arbitrary element and the values of its neighbors. For examp

7条回答
  •  囚心锁ツ
    2020-12-03 01:55

    The typical way to fit values to a certain range is to use the % operator:

    k = l[(i + 1) % len(l)]
    

提交回复
热议问题