You can distinguish Python: "The index and slice" it?

Python type sequence (sequence types) [1] provides a unique index (Indexing) and slice (slicing) mechanism to access an element or a part of the sequence.

[1] 如list, tuple, range, str, bytes, bytearray, memoryview

1. index

In the foregoing method has been demonstrated by using the index to access strings, lists, tuples. Like most other programming languages, Python index starts from 0 (the sequence length N, the index number from 0 to N-1.

In addition, Python by a method of introducing a negative index, so that the writing access sequence is started from the tail is very simple. The last element of the index is -1, -2 penultimate index, and so on, until the index of the first element is -n. End element need only access sequence x [-1] to, without using complicated expressions such as x [len (x) -1].

As shown below.
Here Insert Picture Description

2. slice

Slicing operation and selection from a list of elements sequence type objects, the new object is obtained. In the following example to show the list of the slicing operation shown in FIG.
Here Insert Picture Description

>>> a = [1, 3, 5, 7, 9, 11, 13, 15]
>>> a[3:7]  # [起始元素:结束元素+1]
[7, 9, 11, 13]      
>>> a[:7]       # 省略起始索引,从头开始算起
[1, 3, 5, 7, 9, 11, 13]
>>> a[3:]       # 省略结尾索引,算至末尾
[7, 9, 11, 13, 15]
>>> a[:]
[1, 3, 5, 7, 9, 11, 13, 15]

Adding a third parameter calculation sections can be selected at intervals element.

PS: I encountered a problem no one answer? Requires Python learning materials? Click on the link below you can add yourself get
note.youdao.com/noteshare?id=2dce86d0c2588ae7c0a88bee34324d76

As shown below

Here Insert Picture Description

>>> a = [1, 3, 5, 7, 9, 11, 13, 15]
>>> a[1:7:2]
[3, 7, 11]

When the step is negative, it can be achieved slices "back-to-front" in:

>>> a[::-1]     # 从尾至头,步长为-1
[15, 13, 11, 9, 7, 5, 3, 1]

Slice equally applicable to other types of sequences:

>>> t = (1, 3, 5, 7, 9, 11, 13, 15)
>>> t[2:7:2]    # 元组
(5, 9, 13)
>>> s = 'abcdefgh'
>>> s[::3]  # 字符串
'adg'

Removing the outer lists, tuples, strings, Python also for generating a range of types of arithmetic sequence, a control loop which is used for

Guess you like

Origin www.cnblogs.com/djdjdj123/p/12104432.html