元组与列表类似,不同之处在于元组的元素不能修改,元组用()定义,索引从0开始
注:元组中只包含一个元素时,需要在元素后面添加","
info_tuple = ("zhangsan", 18, 1.75)
# 定义空元组
empty_tuple = ()
# 定义只包含一个元素的元组
single_tuple = (5,)
取值和取索引,取索引就是已经知道数据的内容,希望知道该数据在元组中的索引
print(info_tuple[0])
print(info_tuple.index(18))
统计计数
print(info_tuple.count("zhangsan"))
统计元组中包含元素的个数
print(len(info_tuple))
循环遍历
使用迭代遍历元组
for 循环内部使用的变量 in 元组:
循环内部针对元组元素进行操作
for my_info in info_tuple:
# 使用格式字符串拼接my_info这个变量不方便
# 因为元组中通常保存的数据类型是不同的
print(my_info)
格式化字符串后面的()本质上就是元组
print("%s 年龄是 %d 身高是 %.2f" % info_tuple)
info_str = "%s 年龄是 %d 身高是 %.2f" % info_tuple
print(info_str)
列表和元组之间相互转换
info_1 = ("zhangsan", "lisi")
list_1 = [1, 3, 3, 4]
list(info_1)
tuple(list_1)