引言:
为什么要使用元组呢?
首先,元组是不可修改的,但是列表是可修改的,因此当我们想要输入一些不可修改的数据的时候,列表就不合适了,这时就会用到元组(tuple);
元组的定义:
元组定义:使用小括号,且用逗号隔开各个数据,数据可以是不同的数据类型。
# 定义元组字面量
(元素, 元素, 元素, 元素, ..., 元素)
# 定义元组变量
变量名称 = (元素, 元素, 元素, ..., 元素)
# 定义空元组
变量名称 = () #方式1
变量名称 = tuple() #方式2
# 嵌套元组
t1 = ((1, 2, 3),(4, 5, 6))
"""
Python 中tuple 元组相关操作
"""
t1 = (1, "新年快乐", True)
t2 = ()
t3 = tuple()
print(f"t1的类型是:{type(t1)}, 内容是:{t1}")
print(f"t2的类型是:{type(t2)}, 内容是:{t2}")
print(f"t3的类型是:{type(t3)}, 内容是:{t3}")
注意:
# 定义3个元素的元组
t1 = (1, "Hello", True)
# 定义1个元素的元组
t2 = ('Hello', ) #注意,必须带有逗号,否则不是元组类型
注意:元组只有一个数据,这个数据后面要添加逗号,否则不是元组类型;
元组也支持下标索引查询等等;
元组的操作方法:
下标索引获取内容:
代码展示:
# 普通元组
print("普通元组:")
tuple1 = (1, 2, 3)
print(tuple1[1])
# 嵌套元组
print("嵌套元组:")
tuple2 = ((1, 2, 3), (4, 5, 6))
print(tuple2[1][1])
index 查找方法:
代码展示:
# index 查找方法
tuple1 = (1, 2, 3, 4, 5)
index = tuple1.index(2)
print(f"在元组tuple1 中查找2,下标为:{index}")
count 统计方法:
代码展示:
# count 统计方法
tuple1 = (1, 1, 2, 2, 3, 4, 5)
num = tuple1.count(1)
print(f"在元组tuple1 中统计1的数量有:{num}个")
len 统计元组元素个数:
代码展示:
# len 计算元素全部个数方法
tuple1 = (1, 2, 3, 4, 5)
length = len(tuple1)
print(f"元组tuple1的长度为:{length}")
元组的遍历:
while 循环:
代码展示:
# while 循环遍历
index = 0
tuple1 = (1, 2, 3, 4, 5)
while index < len(tuple1):
print(f"元组元素有:{tuple1[index]}")
index += 1
for 循环:
代码展示:
# for 循环遍历
tuple1 = (1, 2, 3, 4, 5)
for element in tuple1:
print(f"元组的元素有:{element}")
注意:
元组是无法进行修改的,但是如果在元组里面嵌套一个列表的话,那么是可以对列表进行修改的;
代码展示:
t1 = (1, 2, 3, 4, [5, 6, 7, 8, 9])
t1[4][0] = "five"
t1[4][1] = "six"
t1[4][2] = "seven"
print(f"t1的内容是:{t1}")
元组特点:
总结:
小练习:
"""
元组的基本操作
('小黑子',11,【'football', 'rap', 'sing'】)
1. 查询其年龄所在的下标位置
2. 查询学生的姓名
3。 删除学生爱好中的football
4. 增加爱好:coding到list中
"""
t1 = ('小黑子', 11, ['football', 'rap', 'sing'])
index = t1.index(11)
print(f"年龄所在的下标为:{index}")
name = t1[0]
print(f"学生的姓名为:{name}")
del t1[2][0]
print(f"删除football后的元组为:{t1}")
t1[2].append('coding')
print(f"增加后的元组为:{t1}")