Pythonic Circular List

前端 未结 7 1926
闹比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:44

    a = [2,3,5,7,11,13]
    
    def env (l, n, count):
        from itertools import cycle, islice
        index = l.index(n) + len(l)
        aux = islice (cycle (l), index - count, index + count + 1)
        return list(aux)
    

    Behaves as follows

    >>> env (a, 2,1)
    [13, 2, 3]
    >>> env (a,13,2)
    [7, 11, 13, 2, 3]
    >>> env (a,7,0)
    [7]
    

提交回复
热议问题