代码之家  ›  专栏  ›  技术社区  ›  van neilsen

从最后一个元素链接回列表起始索引的列表返回子列表

  •  2
  • van neilsen  · 技术社区  · 6 年前

    例如,给定的索引 3 list = [1,2,3,4,5] ,将返回 [4,5,1] . 或给定的索引 4 带列表= [1,2,3,4,5] ,将返回 [5,1,2] .

    我有以下选择:

    1. return list[index:] + list[:index+3]
    2. return list[index:index+3] + list[:len(list)-index]
    3. return list[index+3:] + list[:len(list)-index]
    4. return list[index:index+3] + list[:max(0 , -1*(len(list)-index-3))]
    
    6 回复  |  直到 6 年前
        1
  •  4
  •   user2390182    6 年前

    modulo operator % :

    lst = [1,2,3,4,5]  # do not shadow built-in 'list'
    
    i = 3
    [lst[x % len(lst)] for x in range(i, i+3)]
    # [4, 5, 1]
    
    i = 4
    [lst[x % len(lst)] for x in range(i, i+3)]
    # [5, 1, 2]
    

    从您给定的选项中,最后一个选项(4.)会产生相同的结果:

    lst[i:i+3] + lst[:max(0 , -1*(len(lst)-i-3))]
    

        2
  •  1
  •   Dani Mesejo    6 年前

    你可以用 cycle

    生成一个迭代器,从iterable返回元素并保存 每份的复印件。当iterable耗尽时,从 保存的副本。

    from itertools import cycle, islice
    
    lst = [1, 2, 3, 4, 5]
    
    
    def get(l, index, length=3):
        return list(islice(cycle(l), index, index + length))
    
    
    print(get(lst, 3))
    print(get(lst, 4))
    

    输出

    [4, 5, 1]
    [5, 1, 2]
    
        3
  •  1
  •   Alex    6 年前

    比如:

    def return_consecutive(a, index, n=3):
        while index > len(a):
            index -= len(a)
        a.extend(a)
        return a [index:index + n]
    
    return_consecutive(a, 3)
    [4, 5, 1]
    return_consecutive(a, 4)
    [5, 1, 2]
    return_consecutive(a, 6)
    [2, 3, 4]
    

        4
  •  1
  •   Albin Paul    6 年前

    >>> l = [1,2,3,4,5]
    >>> def roundlist(l,index,value):
    ...     return (l+l)[index:index+value]
    ... 
    >>> roundlist(l,3,3)
    [4, 5, 1]
    >>> roundlist(l,4,3)
    [5, 1, 2]
    
        5
  •  1
  •   yatu Sayali Sonawane    6 年前

    这可以通过使用 np.roll

    lst = [1,2,3,4,5]
    
    def roll_n(x, index, length=3):
        return np.roll(x,-index)[:length].tolist()
    
    roll_n(lst,3)
    [4, 5, 1]
    
    roll_n(lst,4)
    [5, 1, 2]
    
        6
  •  0
  •   jpp    6 年前

    还有其他方法。例如,您可以使用 collections.deque 通过 deque.rotate itertools.islice

    from collections import deque
    from itertools import islice
    
    L = [1,2,3,4,5]
    k, n = -3, 3
    
    dq = deque(L)
    dq.rotate(k)
    res = list(islice(dq, 0, n))
    
    [4, 5, 1]