Python basics-General sequence operations
Python continue
Python includes six built-in sequences: List, tuples, strings, Unicode strings, buffer objects, and xrange objects. We will introduce it step by step.
Today we will introduce general sequence operations. It's perfect!
1 Index
All programmers know that index subscript starts from scratch, and so does Python. index 0 points to the first element in the sequence.
However, compared with C ++, Python addsNegative IndexThe index of the last element is-1, from right to left is-2,-3...
The string literal value can be directly indexed:
>>>'Hello'[1]e
2 parts
Two indexes are separated by a colon.
>>>str = 'write.blog.csdn.net'>>>str[6,10]blog
Note that the first index is the number of the first element to be extracted, and the last index isRemainingThe number of the first element of the part.
Elegant shortcuts:
The first sequence is known, and the last three elements are accessed.
>>>number = [1,2,3,4,5,6,7,8,9,10]
Method 1:
>>>number[7:10][8,9,10]
Method 2 (failed ):
>>>number[-3:-1][8,9] >>>number[-3:0][]
Note:The leftmost index of a shard appears in the sequence later than the index on the right. The result is an empty sequence.
Method 3:
>>>number[-3:][8,9,10]
Note:If the part obtained contains the elements at the end of the sequence, you can leave the last index empty.
The first index is empty:
>>>number[:3][1,2,3]
If both indexes are left blank, copy the entire sequence:
>>>number[:][1,2,3,4,5,6,7,8,9,10]
Parts of the three parameters:
The third parameter is the step size.
>>>number[::4][1,5,9]
3. Sequence Addition
Do not add different types of Sequences
>>>[1,2,3]+[4,5,6][1,2,3,4,5,6]
4. Sequential Multiplication
The number x is multiplied by a sequence, and the new sequence is generated to repeat the original sequence x times:
>>>'Python'*5'PythonPythonPythonPythonPython'
5. Membership
Check whether a value is in the sequence.In Operator, Returns True or False
>>>permissions = 'rw'>>>'w' in permissionsTrue
6. length, minimum value, and maximum value
Built-in len min max is very useful.
This is no different from C ++, so I will not repeat it here.