Python: Slice character,
Python slice character :( :) 1. Single Slice character
The Slice character of python is used for tuples, strings, or lists. It is left closed and right open, that is, the nth number on the left of the colon, excluding the number on the right. The following is a list example:
>>> a=[1,2,3,4]>>> a[1:][2, 3, 4]>>> a[1:3][2, 3]>>> a[:3][1, 2, 3]>>>
2. Dual-slice characters
Dual-Slice: (: :) is generally used to retrieve several of the elements or replace the list of string tuples. The writing method is also flexible. The following describes:
1) [: N], N can be a positive number or a negative number, and a negative number represents the value from right to left. The absolute value of N represents the number of each other. The following uses a string as an example:
>>> a="abcdefg">>> a[::-1]'gfedcba'>>> a[::-2]'geca'>>> a[::2]'aceg'>>> a[::3]'adg'>>> a[::6]'ag'>>> a[::9]'a'
2) [M: N], and M and N can both be positive and negative. The specific implementation is as follows:
I. When N is positive, it is regarded as [M:] [: N], as follows:
>>> a=(1,2,3,4,5,6,7)>>> a[3::2](4, 6)>>> a[3:][::2](4, 6)
2. When N is negative, it is regarded as taking all values in the inverse direction of the M phase (including the M bit) and then performing the [: N] operation
>>> a=(1,2,3,4,5,6,7)>>> a[4::-2](5, 3, 1)
The above is to take out the 0th to 4 bits of a, and the result is (, 5), and then perform the [: N] operation. The final result is (, 3, 1) when M is a negative value, I will not go into details here.
3) [M: N: k] M and N can both be positive and negative, and k is positive:
>>> a=(1,2,3,4,5,6,7)>>> a[2:-2:3](3,)
A is taken from [2:-2] and the result is (3, 4, 5). Then, one of the three values is taken. The result is (3,) followed by a comma, is to indicate that this is a tuples, rather than a separate 3
3) [M: N: k] M and N can both be positive and negative, and k is negative:
>>> a=[1,2,3,4,5,6,7]>>> a[6:1:-2][7, 5, 3]>>>
When the third digit is a negative number, all values are the opposite of the first two values, that is, 1 to 6 digits. However, because 6 is closed and 1 is open, therefore, the result is [3, 4, 5, 6, 7], and then [:-2]. The result is [7, 5, 3].
The rest will not be repeated.