What does extended slice syntax actually do for negative steps?

This question already has an answer here:

  • Understanding Python's slice notation 29 answers

  • [-1:0:-1] means: start from the index len(string)-1 and move up to 0 (not included) and take a step of -1 (reverse).

    So, the following indexes are fetched:

    le-1, le-1-1, le-1-1-1  .... 1  # le is len(string)
    

    example:

    In [24]: strs = 'foobar'
    
    In [25]: le = len(strs)
    
    In [26]: strs[-1:0:-1]  # the first -1 is equivalent to len(strs)-1
    
    Out[26]: 'raboo'
    
    In [27]: strs[le-1:0:-1]   
    Out[27]: 'raboo'
    

    The Python documentation (here's the technical one; the explanation for range() is a bit easier to understand) is more correct than the simplified "every kth element" explanation. The slicing parameters are aptly named

    slice[start:stop:step]
    

    so the slice starts at the location defined by start , stops before the location stop is reached, and moves from one position to the next by step items.

    链接地址: http://www.djcxy.com/p/26740.html

    上一篇: 1]“在Python中返回一个反转列表?

    下一篇: 扩展切片语法实际上对负向步骤做什么?