The python slices is very convenient, flexible to list, tuple, string, range operation, to obtain the desired data;
Usually we access elements in the sequence, can be accessed through the forward index, the reverse can also be accessed, sliced same can also be, for example I used the following methods of operation:
The syntax for the slice:
[start_index,end_index,step]
start_index: starting index position
end_index: end index position
step: step
Slice features: from a starting position to a position before the end position, in steps to extract the data and generate a new object, and does not change the original data type;
1 For example, write full:
L = [2,4,5,6,2,6,0,4] # 8 length
result = L[2:6:1]
print(result)
Results: [5,6,2,6]
As can be seen, in steps 1, starting from index 2, the index to the end of all the elements 6-1
Note: The above operations also apply to the string or tuple, string reverse display, a microtome can be very easy to do;
For example 2, steps will be omitted:
L = [2,4,5,6,2,6,0,4] # 8 length
result = L[2:6]
print(result)
Results: [5,6,2,6]
As can be seen, the default step size is 1, may be omitted
For example 3, the start index is omitted:
L = [2,4,5,6,2,6,0,4] # 8 length
result = L[:5]
print(result)
Results: [2,4,5,6,2]
As can be seen, in steps 1, starting from the first element to the end of all the elements of the index 5-1
4 example, the end of the index will be omitted:
L = [2,4,5,6,2,6,0,4] # 8 length
result = L[3:]
print(result)
Results: [6,2,6,0,4]
As can be seen, 1, starting with the index element in steps 3, the last element
For example 5, the start, end indexes are omitted:
L = [2,4,5,6,2,6,0,4] # 8 length
result = L[:]
print(result)
Results: [2,4,5,6,2,6,0,4]
It can be seen from the equivalent of the first to the last element, a new copy of the sequence
For example 6, step 1, but non-positive integer:
L = [2,4,5,6,2,6,0,4] # 8 length
result = L[2:6:2]
print(result)
Results: [5,2]
As it can be seen, according to step 2, starting from the index element 2, to the end of all the elements of the index element 6-1
Example 7, step a negative integer:
L = [2,4,5,6,2,6,0,4] # 8 length
result = L[-2:-7:-3]
print(result)
Results: [0,6]
As can be seen, 2, -2 starts indexing elements by the step, the index -7 + 1 to the end of all the elements of the element
Note: when sliced must ensure that the steps and the direction of the beginning, the end of the same direction, otherwise it may get an empty sequence
8 example, the start end is omitted, -1, to obtain a reverse sequence of steps:
L = [2,4,5,6,2,6,0,4] # 8 length
result = L[::-1]
print(result)
Results: [4, 0, 6, 2, 6, 5, 4, 2]
As can be seen, start, end indexes are omitted, you can be a reverse sequence