iT邦幫忙

2025 iThome 鐵人賽

DAY 11
0

今天來說說元組 tuple,其實與串列 List很像,元組 tuple是有序且不可變的資料類型,元組 tuple用一般的()表示,建立好後無法新增、移除、修改等,因為它不可變所以在這點上和串列 List有著不同的區別,至於內容想放什麼就放什麼,沒有特別規定。

建立元組

建立元組可分成幾種方式:

  1. ()
    最直觀的方式就是使用(),這會建立一個空的元組 tuple,在()的元素就會是一般的元組 tuple。
fruits = ()

我們有提到元組 tuple是使用()來表示,那麼在建立時,當內容只有一個元素就必須在尾巴加上,,以免出錯

# 多元素
num = (1, 2, 3)
# 單一元素
num = (1,)
  1. tuple()
    建立空的元組 tuple 或是將其他可迭代物件轉換為元組 tuple。
fruits = tuple()
print(fruits) # ()

傳入可迭代的物件換轉換成元組 tuple。

fruits = tuple(["apple", "banana"])
print(fruits)  # ('apple', 'banana')
  1. 不加()
    這是一種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 提供了內建函式可以做到這事情!
這在處理可變和不可變資料結構時非常有用!

  1. 串列 --> 元組
    轉換後的元組是不可變的,既然不可變表示無法新增、修改、刪除元素,常使用在需要固定資料結構、set()dict()key
fruits = ["apple", "banana", "mango", "lemon", "orange", "tomato"]
new_fruits = tuple(fruits)
print(new_fruits) # ('apple', 'banana', 'mango', 'lemon', 'orange', 'tomato')
  1. 元組 --> 串列
    轉換後的串列是可變的,既然可變就表示可以新增、修改、刪除元素。
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'])

那麼今天就介紹到這,明天見ㄅㄅ!


上一篇
筆記Day10:集合 Set
下一篇
筆記Day12:字典 Dict
系列文
Python 學習筆記12
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言