List slicing with dynamic index on [:index]

前端 未结 4 1194
慢半拍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:15

    You can use None rather than 0 to get the full slice:

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

    My testing:

    import timeit
    
    def jonrsharpe(seq, index):
        return seq[:-index if index else None]
    
    def Cyber(seq, index):
        return seq[:len(arr) - index]
    
    def shashank(seq, index):
        return seq[:-index or None]
    
    if __name__ == '__main__':
        funcs = ('jonrsharpe', 'Cyber', 'shashank')
        arr = range(1000)
        setup = 'from __main__ import arr, {}'.format(', '.join(funcs))
        for func in funcs:
            print func
            for x in (0, 10, 100, 1000):
                print x,
                print timeit.timeit('{}(arr, {})'.format(func, x), setup=setup)
    

    and results:

    jonrsharpe
    0 2.9769377505
    10 3.10071766781
    100 2.83629358793
    1000 0.252808797871
    Cyber
    0 3.11828875501
    10 3.10177615276
    100 2.82515282642
    1000 0.283648679403
    shashank
    0 2.99515364824
    10 3.11204965989
    100 2.85491723351
    1000 0.201558213116
    

提交回复
热议问题