Wrapping around a list as a slice operation

前端 未结 4 2067
野性不改
野性不改 2020-11-27 07:37

Consider the following simple python code

>>> L = range(3)
>>> L
[0, 1, 2]

We can take slices of this array as follows:

4条回答
  •  無奈伤痛
    2020-11-27 08:00

    If you are not overly attached to the exact slicing syntax, you can write a function that produces the desired output including the wrapping behavior.

    E.g., like this:

    def wrapping_slice(lst, *args):
        return [lst[i%len(lst)] for i in range(*args)]
    

    Example output:

    >>> L = range(3)
    >>> wrapping_slice(L, 1, 4)
    [1, 2, 0]
    >>> wrapping_slice(L, -1, 4)
    [2, 0, 1, 2, 0]
    >>> wrapping_slice(L, -1, 4, 2)
    [2, 1, 0]
    

    Caveat: You can't use this on the left-hand side of a slice assignment.

提交回复
热议问题