1. Indexes and slices : In Python, the index of an array is the same as in other languages, and from 0~n-1, the method of using the index is also in brackets, but the use of slices in Python simplifies the code
index : Take out the 3rd element in the array s: x=s[2]
slices : A method of using very little code to process an array element on demand. The slice has a minimum of 1 parameters, with a maximum of 3 parameters, as shown below:
Let's assume that the following array is declared as array=[2,3,4,5,6]
1 Parameters:
- array[1:]--the element from subscript 1 to the last element, returning [4,5,6]
- array[:3]--the element from subscript 0 to an element with subscript 2, excluding the element of subscript 3 , returns [2,3,4]
- array[::2]--starts with an element labeled 0, and the last one that has a subscript corresponding to the 0 index%2
Note : If any of the first 2 parameters are negative, then, in 2 cases, if the negative number is less than-N, then give negative values to 0, if only in-n~0, then it will be understood as 0~n-1 between the circle can be. The algorithm of negative circle, very simple, don't say
2 parameters:
- array[1:-2]--from subscript 1 to all elements before subscript (n-1), return [3,4,5]
- array[-2:3]--returns an empty array when the first argument is calculated to be greater than or equal to the last one []
- array[-13:3]--See the first note above, the first parameter is 0, return [2,3,4]
3 parameters
- [:: -1]--from beginning to end, reverse array, return [6,5,4,3,2]
- [ -1::-2]--from tail to head, each element, select an element, return [6,4,2]
Note : When there is no 3rd parameter, the slice can only be left -to-right, and an empty array is returned if the first parameter is greater than or equal to the second argument
Note : When the third parameter <0, the slice direction can be changed without the above limitation
python--Getting Started series (i) Indexes and slices