python 常用数据结构-元组
Tuple 元组
- 元组定义与使用
- 元组常用方法
- 元组与列表
元组定义
- 元组是有序的不可变对象集合
- 元组使用小括号()包围,各个对象之间使用逗号分隔
- 元组是异构的,可以包含多种数据类型
元组使用:创建
- 创建
- 使用逗号分隔
- 通过小括号填充元素
- 通过构造方法 tuple(iterable)
#1、直接使用逗号分隔
tup1 = 1, 2, 3, 4, 5
print(type(tup1),tup1)
#2、通过小括号填充元素
tup2 = (1, 2, 3, 4, 5)
print(type(tup2),tup2)
#3、通过构造函数tuple(iterable可迭代)
tup3 = tuple()
print(type(tup3),tup3)
tup4 = tuple(‘hogwarts’)
print(type(tup4),tup4)
tup5 = tuple([1,2,3,4,5]) # 赋值为列表对象
print(type(tup5),tup5)
#4、注意:单个元素元组,逗号不可或缺
tup6 = 1,
print(type(tup6),tup6)
tup7 = (2,)
print(type(tup7),tup7)
tup8 = (3) # 输出是个整型
print(type(tup8),tup8)
输出结果为:
<class ‘tuple’> (1, 2, 3, 4, 5)
<class ‘tuple’> (1, 2, 3, 4, 5)
<class ‘tuple’> ()
<class ‘tuple’> (‘h’, ‘o’, ‘g’, ‘w’, ‘a’, ‘r’, ‘t’, ‘s’)
<class ‘tuple’> (1, 2, 3, 4, 5)
<class ‘tuple’> (1,)
<class ‘tuple’> (2,)
<class ‘int’> 3
元组使用:索引
- 索引
- 可以通过索引值来访问对应的元素。
- 正向索引,默认编号从 0 开始
- 反向索引,默认编号从-1 开始
tup9 = tuple(“hogwarts”)
#正向索引
print(tup9[2])
#反向索引
print(tup9[-1])
输出结果为:
g
s
元组使用:切片
- 切片 [start: stop: step]
- 三个值都是可选的,非必填
- start 值: 指示开始索引值,如果没有指定,则默认开始值为 0;
- stop 值:指示到哪个索引值结束,但不包括这个结束索引值。如果没有指定,则取元组允许的最大索引值;
- step 值:步长值指示每一步大小,如果没有指定,则默认步长值为 1。
元组使用:切片实例
“”" 元组切片 “”"
#1、[start:stop:step]
tup10 = (‘hogwarts’)
print(tup10)
print(tup10[:])
print(tup10[0:3:1]) # 从第一个元素到第3个元素,即输出:hog
print(tup10[:-2]) # 从第1个元素到倒数第2个,即输出:hogwar
print(tup10[2:4])
print(tup10[2:5:2])
#特殊的切片写法:逆序
print(tup10[::-1])
输出结果为:
hogwarts
hogwarts
hog
hogwar
gw
ga
strawgoh
元组常用方法
- index()
- count()
元组常用方法 index()
- index(item)
- 返回与目标元素相匹配的首个元素的索引。
-目标必须在元组中存在的,否则会报错
tup11 = (‘hogowarts’)
#1、index(item)
print(tup11.index(‘o’)) # 首个元素的索引 打印 1
print(tup11.index(‘x’)) # 打印 ValueError: substring not found
元组常用方法 count()
- count(item):返回某个元素出现的次数。
- 入参:对象 item
- 返回:次数
tup11 = (‘hogowarts’)
#2、count(item)
print(tup11.count(‘o’)) # 出现的次数 打印 2
元组解包
- 元组解包:把一个可迭代对象里的元素,一并赋值到由对应的变量组成的元组中。
“”“元组解包”“”
tup12 = 1,2,3
#传统逐个赋值的方式
a = tup12[0]
b = tup12[1]
c = tup12[2]
print(a, b, c)
#使用元组解包,一气呵成
a, b, c = (1, 2, 3)
print(a, b, c)
a, b, c = [1, 2, 3]
print(a, b, c)
输出结果为:
1 2 3
1 2 3
1 2 3
元组与列表
- 相同点
-都是有序的
-都是异构的,能够包含不同类型的对象
-都支持索引和切片 - 区别
-声明方式不同,元组使用(),列表使用 []
-列表是可变的,元组是不可变的