您的位置:首页 > 编程语言 > Python开发

Python - 序列(sequence) 详解 及 代码

2013-12-14 07:57 746 查看

序列(sequence) 详解 及 代码

本文地址: http://blog.csdn.net/caroline_wendy/article/details/17314581
序列是Python基础的数据结构, 列表, 元组, 字符串均属于序列;
序列可以使用下标操作符进行操作, 也可以通过冒号(:), 限定范围, 表示切片(slice);
冒号前表示起始位置,缺省为0;
冒号后表示结束位置,缺省为end, 即最后一个元素的下一个元素;
如[a:b], 表示[a, b), 即包含a不包含b, ab的区间;
也可以使用负数进行输出, 表示末尾值减去一个值, 如[0:-a], 表示[0, end-a);
添加第三个参数, 表示步长, 即间隔为多少, 如果步长为负数, 表示逆序;
代码:

# -*- coding: utf-8 -*-  #==================== #File: abop.py #Author: Wendy #Date: 2013-12-03 #====================  #eclipse pydev, python3.3  #序列 sequence  namelist = ['Caroline', 'Wendy', 'Spike', 'Tinny'] #Python的字符串尽量使用('') name = ['Tinny']  #序列索引 print('Item 0 is', namelist[0]) #Python会在字符串和变量之间, 自动生成空格 print('Item -1 is', namelist[-1]) print('Item -2 is', namelist[-2]) print('Character 0 is', name[0])  #序列切片, string类型相似 print('Item 1 to 3 is', namelist[1:3]) #[1,3)即包含1, 不包含3, 注意从0开始 print('Item 2 to end is', namelist[2:]) #后缺省表示end print('Item 1 to -1 is', namelist[1:-1]) #[1,end-1) print('Item start ot end is', namelist[:]) #前后都缺省, 表示全部元素  #指定步长 print('Step 1 is', namelist[::1]) print('Step 2 is', namelist[::2]) print('Step 3 is', namelist[::3]) print('Step -1 is', namelist[::-1]) #即倒序

输出:

Item 0 is Caroline Item -1 is Tinny Item -2 is Spike Character 0 is Tinny Item 1 to 3 is ['Wendy', 'Spike'] Item 2 to end is ['Spike', 'Tinny'] Item 1 to -1 is ['Wendy', 'Spike'] Item start ot end is ['Caroline', 'Wendy', 'Spike', 'Tinny'] Step 1 is ['Caroline', 'Wendy', 'Spike', 'Tinny'] Step 2 is ['Caroline', 'Spike'] Step 3 is ['Caroline', 'Tinny'] Step -1 is ['Tinny', 'Spike', 'Wendy', 'Caroline']




本文出自 “永不言弃” 博客,请务必保留此出处http://spikeking.blog.51cto.com/5252771/1387959
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: