今天來說說元組 tuple
,其實與串列 List
很像,元組 tuple
是有序且不可變的資料類型,元組 tuple
用一般的()
表示,建立好後無法新增、移除、修改等,因為它不可變所以在這點上和串列 List
有著不同的區別,至於內容想放什麼就放什麼,沒有特別規定。
建立元組可分成幾種方式:
()
()
,這會建立一個空的元組 tuple,在()
的元素就會是一般的元組 tuple。fruits = ()
我們有提到元組 tuple
是使用()
來表示,那麼在建立時,當內容只有一個元素就必須在尾巴加上,
,以免出錯
# 多元素
num = (1, 2, 3)
# 單一元素
num = (1,)
tuple()
fruits = tuple()
print(fruits) # ()
傳入可迭代的物件換轉換成元組 tuple。
fruits = tuple(["apple", "banana"])
print(fruits) # ('apple', 'banana')
()
tuple packing
打包的語法,在 Python 中只要看到逗號 ,
,就會自動建立一個元組 tuple,即使沒有()
也是!()
一樣有區分單一元素和多元素的差別,單一元素仍需要在尾巴加上,
才行。fruits = 1, 2, 3
print(fruits) # (1, 2, 3)
元組是有順序性的,那麼就可以利用索引值取得指定內容,使用方式和串列一樣使用[]
即可。
fruits = ("apple", "banana", "mango", "lemon", "orange", "tomato")
print(fruits[1]) # banana
print(fruits[-1]) # tomato
使用方法和串列一樣使用符號+
就可將兩元組串接起來。
first_fruits = ("apple", "banana", "mango", "lemon")
second_fruits = ("orange", "tomato")
print(first_fruits + second_fruits) # ('apple', 'banana', 'mango', 'lemon', 'orange', 'tomato')
在這邊可以使用先前所提到的運算子in
來處理,該回傳結果會是布林值。
fruits = ("apple", "banana", "mango", "lemon", "orange", "tomato")
print("tomato" in fruits) # True
這兩者之間是可以相互轉換的,Python 提供了內建函式可以做到這事情!
這在處理可變和不可變資料結構時非常有用!
set()
、dict()
的key
。fruits = ["apple", "banana", "mango", "lemon", "orange", "tomato"]
new_fruits = tuple(fruits)
print(new_fruits) # ('apple', 'banana', 'mango', 'lemon', 'orange', 'tomato')
fruits = ("apple", "banana", "mango", "lemon", "orange", "tomato")
new_fruits = list(fruits)
print(new_fruits) # ['apple', 'banana', 'mango', 'lemon', 'orange', 'tomato']
如果要刪除元組要特別注意!因為元組是不可變的,當然就無法對元素進行刪除,刪除本身也屬於一種『變更』的行為,但我們可以使用del
直接刪除這個元組本身。
fruits = ("apple", "banana", "mango", "lemon", "orange", "tomato")
del fruits
print(fruits) # NameError: name 'fruits' is not defined
雖然說tuple
是不可變的,但tuple
中有可變的資料型態還是可以操作的。
fruits = ("apple", 100, ["orange", "peach", "banana"])
fruits[-1][1] = "mango"
print(fruits) # ('apple', 100, ['orange', 'mango', 'banana'])
那麼今天就介紹到這,明天見ㄅㄅ!