Home  >  Article  >  Backend Development  >  python-slicing

python-slicing

高洛峰
高洛峰Original
2016-11-21 18:09:281187browse

Getting a part of a list or tuple is a very common operation. In addition to using loops to obtain elements one by one through index, python also provides us with the convenient slice (Slice) operator:.

We define a list for the following examples.

L = ['apple','banaba','peal','orange','water melon']

Take an element

Take an element in order

For example, L[1] represents the 2nd element , that is, the element with index 1.

Get an element in reverse order

List, tuple, string, etc. can not only take elements from the beginning, but also start from the end. For example:
list[-1] refers to the last one in the list.

Get multiple elements

Get multiple elements from the beginning

print L[0:3]
        ||____切片结束index,但是不包括该index的元素。
        |____切片起始index。包括该index的元素。
        
# 上述即取L这个list的index为0、1、2的三个元素。
        
print L[ :3]
        |___切片开始的index不填则默认是从list最前端即index=0开始。(事实上也不用空一格,这里只是展示方便。)

The output of the above two print functions are ['apple', 'banaba', 'peal']. The slicing symbol is a pair of

take multiple elements starting from the end

For example

L[-3:-1]
   |  |____倒数第1个结束,但不包括该元素。
   |_____倒数第3个开始,包括该元素。

Wow, we found a rule:
When python slices, it always includes the previous element, but does not include the last element.
Of course, slicing starts from the end, and omitting the index means cutting all the way to the end. For example:

L[-3:]

Suddenly had a magical idea. When slicing, the starting and ending indexes are omitted. So what will happen?
That is, L[:], the answer is to cut out a list that is exactly the same as the original list.

All the examples above are illustrated using lists. In fact, tuple and string are the same. Other programming languages ​​​​such as python and java provide many functions for manipulating strings. In fact, python can use slicing to easily accomplish this.

Note

When python slices, the from in [from:to] must be smaller than to, so that the correct slice will be returned. Otherwise, an empty list, tuple or nothing will be returned (for string slicing) when).


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn