Python元組tuple(不可變)
Python元組 Tuple (不可變):
元組的特點 :
1.元組的初始化:
tuple = (1, ) #元組只有一個元素的話,初始化時要加,否則當做元素的普通變數型別處理
tuple = (1, 2, 3, [2,4,5]) #可以使不同型別的元素
2.元組中的元素不能被修改:
tuple[2] = 5 #錯誤的,編譯不通過,會報錯
3.用 1 中的 tuple ,只不能改變 [2,4,5] 列表元素的地址,但可以通過讀取其地址改變其列表中的值。
一 . 元組的運算 :
1.元組的組合: tuple3 = tuple1 + tuple2
2.元組的重複: print ( tuple * 3 )
3.判斷元素是否在其中: in or not in
4.元組的擷取: [start : ] [ : end] [start : end]
5.二維元組: ((...), (...), ...)
讀取: tuple[1][2]
二 . 相關函式(相比 List 比價少,因為不可變) :
1.len(tuple):返回 tuple 中的元素個數。
2.max(tuple):返回 tuple 中的最大值。
3.min(tuple):返回 tuple 中的最小值。
三 . 和 List 的轉換 :
tuple = tuple(list)
四 .和 List 比的優點:
為什麼有了 List還需要 tuple ,因為 tuple 是不可變的,可以使程式更加的安全 ,因此能用 tuple 就用 tuple ,當然 List 也有它可以變的優勢,將 List 和 tuple 相互轉換結合起來運用更好!!!