Slicing and truncating sequences in python

高洛峰
Release: 2017-02-28 16:16:40
Original
1506 people have browsed it

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]
Copy after login

1. Get the first 3 elements of the list

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

2. Get the last 3 elements of the list

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

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]
Copy after login

4.Specify the growth step

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

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])
Copy after login

The output result is:

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

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template