Python数据类型之元组类型
元组的概念
元组(tuple),是一个有序且不可变的容器,在里面可以存放多个不同类型的元素。和列表(list)的区别在于列表中的数据是可变的。
创建元组:
使用小括号定义元组,元组中的数据可以是不同的数据类型。
# 定义多个数据的元组
tup1 = (10, 20, "aa", True)
print(tup1) # (10, 20, 'aa', True)
print(type(tup1)) # <class 'tuple'>
# 定义单个数据元组,必须有逗号
# 方式1
tup2 = (10,)
print(type(tup2)) # <class 'tuple'>
# 方式2
t1 = 1,
print(t1) # (1,)
print(type(t1)) # <class 'tuple'>
# 如果定义的元组只有一个数据但是没有逗号,则数据类型为这个唯一的数据的类型。
tup3 = (10)
print(type(tup3)) # <class 'int'>
# 定义空元组
# 方式1
tup4 = ()
print(len(tup4)) # 0
print(type(tup4)) # <class 'tuple'>
# 方式2
tup44 = tuple()
print(len(tup44)) # 0
print(type(tup44)) # <class 'tuple'>
切记: 元组的数据是不可以更改的。
元组的下标
元组(tuple)和列表(list)一样使用方括号加下标的方式访问元素。
tup1 = ("tom", "jerry")
print(tup1[0]) # tom
# 超过下标会报异常
print(tup1[2]) # IndexError: tuple index out of range
元组的切片
元组(tuple)和列表(list)一样存在切片操作。
tup1 = ("tom", "jerry", "tomas", "lisa")
print(tup1[0:1]) # ('tom',)
print(tup1[:-1]) # ('tom', 'jerry', 'tomas')
print(tup1[:-1:2]) # ('tom', 'tomas')
print(tup1[::-1]) # ('lisa', 'tomas', 'jerry', 'tom')
元组常见的方法
len()
获取元组的长度。
tup1 = ("tom", "jerry", "tom", "lisa")
print(len(tup1)) # 4
index()
返回指定数据首次出现的索引下标。
tup1 = ("tom", "jerry", "tomas", "jerry")
print(tup1.index("jerry")) # 1
count()
统计指定数据在当前元组中出现的次数。
tup1 = ("tom", "jerry", "tom", "lisa")
print(tup1.count("tom")) # 2
元组常见的操作
元组和列表有类似的特殊操作。
+
: 两个元组组合生成新的元组。
tup1 = (10, 20, 30)
tup2 = (40, 50, 60)
print(tup1+tup2) # (10, 20, 30, 40, 50, 60)
*
: 重复元组。
tup1 = ("tom", "jerry")
print(tup1*2) # ('tom', 'jerry', 'tom', 'jerry')
in
:判断元素是否存在。
tup1 = ("tom", "jerry")
print("tom" in tup1) # True
print("toms" in tup1) # False
not in
: 判断元素是否不存在。
tup2 = ("tom", "jerry", "jack")
print("tom" not in tup2) # False
print("toms" not in tup2) # True
元组嵌套列表
元组不允许修改、新增、删除某个元素。但当元组中嵌套列表时,情况就会不一样。
tup1 = ("a", "b", ["c", "d"])
print(tup1[2][1]) # d
# 当修改元组内部的列表时,可以修改成功。
tup1[2][1] = "xiaoming"
print(tup1) # ('a', 'b', ['c', 'xiaoming'])
所以我们在使用元组时,尽量使用数字、字符串和元组这种不可变的数据类型作为元组的元素,这样就能确保元组的不可变性。
元组的遍历
使用for循环
tup1 = ("a", "b", "c", "d")
for i in tup1:
print(i)
使用for循环和range()
tup1 = ("a", "b", "c", "d")
for i in range(len(tup1)):
print(tup1[i])
使用enumerate()函数
tup1 = ("a", "b", "c", "d")
for index, value in enumerate(tup1):
print(value)
使用内置函数iter()
tup1 = ("a", "b", "c", "d")
for value in iter(tup1):
print(value)