Pythonic Circular List

前端 未结 7 1894
闹比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 02:05

    You could use the modulo operator!

    i = len(l) - 1
    jIndex = (i - 1) % len(l)
    kIndex = (i + 1) % len(l)
    
    j = l[jIndex]
    k = l[kIndex]
    

    Or, to be less verbose:

    k = l[(i + 1) % len(l)]
    
    0 讨论(0)
提交回复
热议问题