pyhon_元组(tuple)
定义: 元组中可以存储不一样类型的数据,使用小括号存储数据,中间用逗号进行分割。 元组中的数据定义好后,无法进行修改,有保护数据的目的。
格式化字符串定义多个值的时候,本质上也是元组。
测试:
info_tuple = ("小明", 24, 1.75)
print("名字是:%s , 年龄:%d , 身高:%.2f" %("小明", 24, 1.75)) # %("小明", 24, 1.75) 其实就是元组
print("名字是:%s , 年龄:%d , 身高:%.2f" %info_tuple)
test = "名字是:%s , 年龄:%d , 身高:%.2f" %info_tuple
print(test) # 元组可以直接定义到变量里面进行数据拼接
输出为:
名字是:小明 , 年龄:24 , 身高:1.75 名字是:小明 , 年龄:24 , 身高:1.75 名字是:小明 , 年龄:24 , 身高:1.75
1 ,定义一个空元组(一般不会定义空元组)
empty_tumple = ()
2, 定义只有一个数据的元组。
single_tuple = (1,) #单个数据后面加个逗号
3,使用index查询元组中的值
info_tuple = ("张三", 1, 2.89)
print(info_tuple[0]) # 使用index值搜索元组中的值,元组所搜寻的索引必须为中括号
4,使用元组中的值取索引方法
info_tuple = ("张三", 1, 2.89)
print(info_tuple.index(2.89)) # 查询元组中2.89对应的index号
5,统计数据在元组中的个数
info_tuple = ("张三", 1, 2.89, "张三")
print(info_tuple.count("张三")) # 统计张三在元组中的个数
6,统计元组的数据个数 使用len方法
info_tuple = ("张三", 1, 2.89, "张三")
print(len(info_tuple)) # 统计元组的数据个数

浙公网安备 33010602011771号