List slicing with dynamic index on [:index]

前端 未结 4 1193
慢半拍i
慢半拍i 2020-12-06 17:34

I need to slice a list using negative dynamic indexes ([:-index]). This was easy until I realized that if the value of my dynamic index was 0, no items were returned, instea

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-06 18:22

    Another potential solution for fun.

    >>> arr = [1, 2, 3]
    >>> index = 0
    >>> arr[:-index or None]
    [1, 2, 3]
    >>> index = 1
    >>> arr[:-index or None]
    [1, 2]
    

    For higher performance on immutable sequence types like strings, you can avoid slicing the sequence entirely in the case that index is 0 by checking the value of index before the slice operation.

    Here's three functions to test in terms of performance:

    def shashank1(seq, index):
        return seq[:-index or None]
    
    def shashank2(seq, index):
        return index and seq[:-index] or seq
    
    def shashank3(seq, index):
        return seq[:-index] if index else seq
    

    The latter two should be much faster in the case where index is 0, but may be slower (or faster) in other cases.


    Updated benchmark code: http://repl.it/oA5

    Note: The results depend quite a bit on the Python implementation.

提交回复
热议问题