现在的位置: 首页 > 综合 > 正文

【Python基础学习篇】Python序列

2018年01月28日 ⁄ 综合 ⁄ 共 1197字 ⁄ 字号 评论关闭

序列是具有索引和切片功能的集合。元组、列表和字符串具有通过索引访问某个具体的值,或通过切片返回一段切片的能力,因此元组、列表和字符串都属于序列

例子:序列的索引功能

#!/usr/bin/env python
# -*- coding=utf-8 -*-
#Using GPL v3.3
#Author: leexide@126.com
#索引操作
tuple = ("apple","banana","grape","orange")
list = ["apple","banana","grape","orange"]
str = "apple"
print tuple[0]
print tuple[-1]
print list[0]
print list[-1]
print str[0]
print str[-1]

输出结果:

---------- python2.7 ----------
apple
orange
apple
orange
a
e

输出完成 (耗时 0 秒) - 正常终止

例子:序列的分片功能

#!/usr/bin/env python
# -*- coding=utf-8 -*-
#Using GPL v3.3
#Author: leexide@126.com
#分片操作
tuple = ("apple","banana","grape","orange")
list = ["apple","banana","grape","orange"]
str = "apple"
print tuple[:3]
print tuple[3:]
print tuple[1:-1]
print tuple[:]
print list[:3]
print list[3:]
print list[1:-1]
print list[:]
print str[:3]
print str[3:]
print str[1:-1]
print str[:]

输出结果:

---------- python2.7 ----------
('apple', 'banana', 'grape')
('orange',)
('banana', 'grape')
('apple', 'banana', 'grape', 'orange')
['apple', 'banana', 'grape']
['orange']
['banana', 'grape']
['apple', 'banana', 'grape', 'orange']
app
le
ppl
apple

输出完成 (耗时 0 秒) - 正常终止

注意:

分片seq[:3]表示从序列第1个元素到第3个元素,分片[:]获得整个序列的值。

元组和列表都具有序列的特性,但是它们的区别也比较明显。

1、元组是只能读的一组数据,而且元组没有提供排序和查找的方法。

2、列表的数据既可以读,也可以写,而且提供了丰富的操作方法,支持排序、查找操作。

3、元组和列表的区别

  支持负索引 支持分片 支持添加、删除、修改 支持排序、查找 数据的组成
元组 一组不同含义的数据
列表 一组相同含义的数据

抱歉!评论已关闭.