1. 程式人生 > >Python 元組,元組的定義,元組與列表的轉換,元組的應用場景

Python 元組,元組的定義,元組與列表的轉換,元組的應用場景

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)