I don't understand slicing with negative bounds in Python. How is this supposed to work?

后端 未结 7 695
臣服心动
臣服心动 2020-12-31 02:19

I am a newbie to Python and have come across the following example in my book that is not explained very well. Here is my print out from the interpreter:

>         


        
7条回答
  •  抹茶落季
    2020-12-31 03:01

    >>> l = ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqr', 'stu', 'vwx', 'yz&']
    
    # I want a string up to 'def' from 'vwx', all in between
    # from 'vwx' so -2;to 'def' just before 'abc' so -9; backwards all so -1.
    >>> l[-2:-9:-1]
    ['vwx', 'stu', 'pqr', 'mno', 'jkl', 'ghi', 'def']
    
    # For the same 'vwx' 7 to 'def' just before 'abc' 0, backwards all -1
    >>> l[7:0:-1]
    ['vwx', 'stu', 'pqr', 'mno', 'jkl', 'ghi', 'def']
    

    Please do not become listless about list.

    1. Write the first element first. You can use positive or negative index for that. I am lazy so I use positive, one stroke less (below 7, or -3 for the start).
    2. Index of the element just before where you want to stop. Again, you can use positive or negative index for that (below 2 or -8 for stop).
    3. Here sign matters; of course - for backwards; value of stride you know. Stride is a 'vector' with both magnitude and direction (below -1, backwards all).

      l = [0,1,2,3,4,5,6,7,8,9]
      l[7:2:-1], l[-3:2:-1], [-3:-8:-1],l[7:-8:-1]
      

      All result in [7, 6, 5, 4, 3].

提交回复
热议问题