2018年5月27日 星期日

[ Python 常見問題 ] Understanding Python's slice notation

Source From Here 
Question 
I need a good explanation (references are a pluson Python's slice notation. To me, this notation needs a bit of picking up. 
It looks extremely powerful, but I haven't quite got my head around it. 

How-To 
It's pretty simple really: 
  1. a[start:end] # items start through end-1  
  2. a[start:]    # items start through the rest of the array  
  3. a[:end]      # items from the beginning through end-1  
  4. a[:]         # a copy of the whole array  
There is also the step value, which can be used with any of the above: 
  1. a[start:end:step] # start through not past end, by step  
The key point to remember is that the :end value represents the first value that is not in the selected slice. So, the difference between end and start is the number of elements selected (if step is 1, the default). The other feature is that startor end may be a negative number, which means it counts from the end of the array instead of the beginning. So: 
  1. a[-1]    # last item in the array  
  2. a[-2:]   # last two items in the array  
  3. a[:-2]   # everything except the last two items  
Similarly, step may be a negative number: 
  1. a[::-1]    # all items in the array, reversed  
  2. a[1::-1]   # the first two items, reversed  
  3. a[:-3:-1]  # the last two items, reversed  
  4. a[-3::-1]  # everything except the last two items, reversed  
Let's take a look at real example: 
>>> alist = list(range(10))
>>> alist
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> alist[3:] # Skip first 3 items
[3, 4, 5, 6, 7, 8, 9]
>>> alist[:-3] # Skip last 3 items
[0, 1, 2, 3, 4, 5, 6]
>>> alist[::-1] # Reverse the list
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> alist[:-3:-1] # Inverse the list and then select element until meet '7'
[9, 8]
>>> alist[-3::-1] # Inverse the list and start from '7'
[7, 6, 5, 4, 3, 2, 1, 0]


Supplement 
What does list[x::y] do? [duplicate] 

沒有留言:

張貼留言

[Linux 常見問題] What's the best way to send a signal to all members of a process group?

Source From  Here   Question   I want to  kill a whole process tree.  What is the best way to do this using any common scripting languages? ...