Pythonic Circular List

前端 未结 7 1925
闹比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:46

    In case you do not want to wrap around, the most Pythonic answer would be to use slices. Missing neighbor substituted with None. E.g.:

    def nbrs(l, e):
       i = l.index(e)
       return (l[i-1:i] + [None])[0], (l[i+1:i+2] + [None])[0]
    

    This is how the function can work:

    >>> nbrs([2,3,4,1], 1)
    (4, None)
    >>> nbrs([1,2,3], 1)
    (None, 2)
    >>> nbrs([2,3,4,1,5,6], 1)
    (4, 5)
    >>> nbrs([], 1)
    Traceback (most recent call last):
      File "", line 1, in 
      File "", line 2, in nbrs
    ValueError: 1 is not in list
    

提交回复
热议问题