python中元组tuple详细解析

1、元组一旦定义不能修改

2、可以定义空元组

empty_tuple = ()

3、元组中只有一个数据时末尾要加英文逗号

single_tuple = (6,)

4、元组取值和取索引
info_tuple = ("zhangsan",18,1.75)

#  取值

print(info_tuple[1])

# 取索引

print(info_tuple.index(18))

# 返回结果

18
1

5、统计计数 count方法统计包含元素的个数

info_tuple = ("zhangsan",18,1.75)

print(info_tuple.count("zhangsan"))

# 返回结果

1

6、统计元组中包含的元素个数 len

info_tuple = ("zhangsan",18,1.75)

print(len(info_tuple))

# 返回结果

3

7、元组的遍历

info_tuple = ("zhangsan",18,1.75)

for temp in info_tuple:
    print(temp)

# 输出结果

zhangsan
18
1.75


# 元组中通常保存的数据类型不同,所以不方便使用格式化字变量
# 在实际开发中,除非知道元组中的数据类型,否则很少使用遍历

  

原文地址:https://www.cnblogs.com/hm-baobao/p/10058285.html