Home  >  Article  >  Backend Development  >  Slicing and truncating sequences in python

Slicing and truncating sequences in python

高洛峰
高洛峰Original
2017-02-28 16:16:401503browse

Sequence concept

In the sharding rules, list, tuple, and str (string) can all be called sequences, and they can all be sliced ​​according to the rules

Slicing operation

Note that the subscript 0 of the slice represents the first element in sequence, -1 represents the first element in reverse order; and the slice does not include the right boundary , for example [0:3] represents elements 0, 1, 2 excluding 3.

l=['a','b','c','d',5]

1. Get the first 3 elements of the list

>>> l[0:3]
['a', 'b', 'c']
>>> l[:3]
['a', 'b', 'c']

2. Get the last 3 elements of the list

>>> l[-3:]
['c', 'd', 5]

Since the list does not include the right boundary, So just take the right boundary of the last three elements and leave it unspecified.

3. Get all elements

>>> l[:]
['a', 'b', 'c', 'd', 5]
>>> l[0:]
['a', 'b', 'c', 'd', 5]

4.Specify the growth step

>>> L=list(range(100))
>>> L[0:101:10]
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]

Specify 10 steps as the unit

Other slices

#!/usr/bin/env python3
#-*- coding:utf-8 -*-
vlist=['a','b','c']
vtuple=('a','b','c')
vstr='abc'
print (vlist[0:2]);
print (vtuple[0:2]);
print (vstr[0:2])

The output result is:

======================== RESTART: C:/Python35/list.py ========================
['a', 'b']
('a', 'b')
ab

For more articles related to fragmentation and truncation of sequences in python, please pay attention to the PHP Chinese website!

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