Python 元组() (元素不能修改),元组的定义,元组与列表的转换,元组的应用场景

学习参考:http://www.runoob.com/python3/python3-tuple.html

demo.py(元组的定义,元组的基本使用):


# 定义元组。如果元组只有一个元素,要在元素后加一个逗号 (5,)  如果不加逗号,解释器不会将小括号当成元组。
info_tuple = ("zhangsan", 18, 1.75, "zhangsan")

# 1. 取值
print(info_tuple[0])

# 2. 取索引。返回数据在元组中第一次出现的索引。数据不存在会报错
print(info_tuple.index("zhangsan"))

# 3. 统计指定数据在元组中出现的次数。
print(info_tuple.count("zhangsan"))

# 4. 统计元组中包含元素的个数 (元组的长度)
print(len(info_tuple))

demo.py(元组的遍历,一般不遍历元组):

info_tuple = ("zhangsan", 18, 1.75)

# 使用for迭代遍历元组
for my_info in info_tuple:

    # 使用格式字符串拼接 my_info 这个变量不方便!
    # 因为元组中通常保存的数据类型是不同的! (所以一般不遍历元组)
    print(my_info)

demo.py(元组的应用,格式化字符串):

info_tuple = ("小明", 21, 1.85)

# 格式化字符串后面的 `()` 本质上就是元组
print("%s 年龄是 %d 身高是 %.2f" % info_tuple)

info_str = "%s 年龄是 %d 身高是 %.2f" % info_tuple

print(info_str)

猜你喜欢

转载自blog.csdn.net/houyanhua1/article/details/83928160