Catalog
Basic concepts
The number in the slice operator
Negative numbers in the slice operator
Slice operation of tuples
String slicing operation
The slice operator is the list name followed by a square bracket , There is a pair of optional numbers in square brackets , And use colons to separate . Note that this is very similar to the index operator you use . Remember that numbers are optional , And a colon is a must .
Be careful : You can also access tuples and strings in the same way .
Let's create a 0-99 Sequence of numbers :
L = list(range(100))
L by :[0, 1, 2, 3, ..., 99]
You can easily take out a certain sequence by slicing .
front 10 Number : L[:10]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
front 11-20 Number : L[10:20]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
after 10 Number : L[-10:]
[90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
First number ( Before the colon ) Indicates where the slice begins ,
The second number ( After the colon ) Indicates where the slice ends ,
The third number ( After the colon ) Indicates the number of slice intervals .
If you don't specify the first number ,Python From the beginning of the sequence .
If the second number is not specified , be Python Will stop at the end of the sequence .
Be careful , The sequence returned starts at the start position , Just before the end position .
That is, the starting position is included in the sequence slice , And the end position is excluded from the slice .
【 Left open closed 】
for example :
list :shoplist=[0,1,2,3,4,5,6,7,8],shoplist[1:3] return :
From the position 1 Start , Including the location 2, But stop at position 3 A sequence slice of , So return a slice with two items .shoplist[:] return : A copy of the entire sequence .
shoplist[::3] return : Location 3, Location 6, Location 9… Sequence slice of .
Negative numbers are used at the end of the sequence .
shoplist[:-1] return : Contains the sequence slice of all items except the last item ,
shoplist[::-1] return : Reverse sequence slice .
tuple It is also a kind of list, The only difference is tuple immutable .
therefore ,tuple It can also be sliced , Just the result of the operation is still tuple:
(0, 1, 2, 3, 4, 5)[:3]
The result is :(0, 1, 2)
character string 'xxx' It can also be seen as a kind of list, Each element is a character .
therefore , Strings can also be sliced , Just the result of the operation is still a string :
'ABCDEFG'[:3]
The result is :'ABC'
'ABCDEFG'[::2]
The result is :'ACEG'
In many programming languages :
There are many kinds of intercepting functions for Strings ( for example ,substring), In fact, the purpose is to slice strings .
Python There is no intercepting function for Strings , You just need to slice one operation to complete , It's simple .
項目介紹隨著社會的發展,In recent years, m
I. Error analysisRunning YOLOv