元组的定义
-
Tuple(元组)与列表类似,不同之处在于元组的元素不能修改
元组表示多个元素组成的序列
元组在Python开发中,有特定的应用场景 -
用于存储一串信息,数据之间使用使用 , 分割
-
元组用 ( ) 定义
-
元组的索引从0开始
索引就是数据在元组中位置的编号
定义一个简单的元组
info_tuple=("zhangsan",18,1.75)
print(info_tuple)
print(info_tuple[0])
print(info_tuple[1])
print(info_tuple[2])
#结果
('zhangsan', 18, 1.75)
zhangsan
18
1.75
定义一个空元组
empty_tuple=()
定义只包含一个元素的元组
#根据结果知道这是不对的
single_tuole=(5)
print(type(single_tuole))
#结果
<class 'int'>
#这种定义方式才是定义单元素元组的正确方式
single_tuole=(5,)
print(type(single_tuole))
#结果
<class 'tuple'>
元组的常用操作
取元组中元素的索引(利用元素值获取索引)
info_tuple=("zhangsan",18,1.75)
print(info_tuple.index('zhangsan'))
print(info_tuple.index(18))
#结果
0
1
获取元组中某个元素的个数
info_tuple=("zhangsan",18,1.75,18)
print(info_tuple.count('zhangsan'))
print(info_tuple.count(18))
#结果
1
2
获取元组中元素的总个数
info_tuple=("zhangsan",18,1.75,18)
print(len(info_tuple))
#结果
4
元组元素的循环遍历
info_tuple=("zhangsan",18,1.75,18)
for i in info_tuple:
print(i)
#结果
zhangsan
18
1.75
18
列表和元组的相互转换
num_list=[1,2,3,4]
print(type(num_list))
num_list=tuple(num_list)
print(type(num_list))
num_list=list(num_list)
print(type(num_list))
#结果
<class 'list'>
<class 'tuple'>
<class 'list'>