1. 定义与特性
1.1 定义
与列表类似,只不过要把[]
改成()
1.2 特性
- 可存放多个值
- 不可变;即tpl[0]='xxx’这种方式是不允许的
- 按照从左到右的顺序定义元组元素,下标从0开始顺序访问,有序
2. 元组的创建
# 方式一:
tpl01 = ('a',1,'1','abc')
# 方式二:
tpl02 = tuple(('b',2,'2','bcd'))
# 方式三:
tpl03 = 'a','b',1,'abc'
print(tpl01) # ('a', 1, '1', 'abc')
print(tpl02) # ('b', 2, '2', 'bcd')
print(tpl03) # ('a', 'b', 1, 'abc')
3. 元组的常用方法
常用方法列表
方法 | 作用 | 语法 |
---|---|---|
索引取元素 | 通过索引获取元组的元素 | tpl[index] |
切片 | 截取指定元素组成新元组 | tpl[start:end:step] |
in/not in | 判断元组中是否包含某元素 | item in tpl;item not in tpl |
index | 从元素中找出某一个值第一个匹配项的索引位置 | tpl.index(value, start=None, stop=None) |
count | 统计某个元素在元组中出现的次数 | tpl.count(value) |
len | 返回元组长度/元素个数 | len(tpl) |
循环 | for循环 | for i in tpl:pass |
常用函数类表
函数 | 作用 | 语法 |
---|---|---|
cmp | 比较两个元组的元素 | cmp(lst1,lst2) |
len | 获取元组元素个数 | len(lst) |
max | 返回元组元素最大值 | max(lst) |
min | 返回元组元素最小值 | min(lst) |
常用方法介绍
# 元组的常用方法
# 1.通过索引获取元素
# 作用:获取指定索引位置的元素
# 返回值:元素本身
# 语法:tpl[index]
# 参数说明:
# index:索引值,从左至右排序,从0开始
tpl = ('a',1,'1','abc')
ret11 = tpl[2]
print('ret11:',ret11)
# 2.切片
# 作用:截取需要的元素组成新的元组(左包右不包)
# 返回值:元组
# 语法:tpl[start:end:step]
# 参数说明:
# start:开始位置
# end:结束位置
# step:步长,隔step-1个元素取一个
tpl = ('abc',12,'e','123','周末','python','linux')
ret21 = tpl[1:3]
ret22 = tpl[1:6:2]
ret23 = tpl[::-1] # 倒序形成新的列表
ret24 = tpl[:-3] # 截取到倒数第三个(左包右不包)
print('ret21:',ret21)
print('ret22:',ret22)
print('ret23:',ret23)
print('ret24:',ret24)
# 3.包含 in/not in
# 作用:判断元组中是否包含某元素
# 返回值:True或False
# 语法:item in tpl;item not in tpl
tpl = ('abc',12,'e','123')
print('ret31:','12' in tpl)
print('ret32:',12 in tpl)
print('ret33:','12' not in tpl)
# 4.index方法
# 作用:从元素中找出某个值第一个匹配项的索引位置
# 返回值:索引值
# 语法:tpl.index(value, start=None, stop=None)
tpl = ('abc',12,'e','123','e')
ret41 = tpl.index('e')
print('ret41:',ret41)
# 5.count方法
# 作用:统计某个元素在元组中出现的次数
# 返回值:元素的次数
# 语法:tpl.count(value)
tpl = ('abc','1',1,'abc')
ret51 = tpl.count('abc')
print('ret51:',ret51)
# 6.len函数
# 作用:返回元组的长度/元素个数
# 返回值:元素个数
# 语法:len(tpl)
tpl = ('abc',12,'e','123')
print('len方法:',len(tpl))
# 7.循环
tpl = ('abc',12,'e','123')
print('循环显示列表元素:')
for i in tpl:
print(i)
print('循环结束')
打印输出结果
'''
ret11: 1
ret21: (12, 'e')
ret22: (12, '123', 'python')
ret23: ('linux', 'python', '周末', '123', 'e', 12, 'abc')
ret24: ('abc', 12, 'e', '123')
ret31: False
ret32: True
ret33: True
ret41: 2
ret51: 2
len方法: 4
循环显示列表元素:
abc
12
e
123
循环结束
'''