這篇文章是閱讀Asabeneh的30 Days Of Python: Day 6 - Tuples後的學習筆記與心得。
元組(tuple)類似串列(list),但是用圓括弧內()
包覆,並且資料不可改動(immutable);JavaScript(以下簡稱JS)中類似的呈現會像Object.freeze([])
。
嘗試改動元組中的元素會產生TypeError
empty_tuple = ()
empty_tuple = tuple()
beverage = ("coffee", "black tea", "milk", "beer")
使用len()
函式*
* 原文是寫方法(method),但官方文件中是放在Build-in Functions下
beverage = ("coffee", "black tea", "milk", "beer")
len(beverage) # 4
這邊跟串列一樣?:
beverage = ("coffee", "black tea", "milk", "beer")
beverage[1] # 'black tea'
beverage[-2] # 'milk'
這邊還是跟串列一樣:
beverage = ("coffee", "black tea", "milk", "beer")
beverage[0:2] # ('coffee', 'black tea')
beverage[-2:] # ('milk', 'beer')
使用list(tuple)
函式進行轉換:
beverage = ("coffee", "black tea", "milk", "beer")
beverage_list = list(beverage)
beverage_list[0] = "apple juice"
print(beverage_list) # ['apple juice', 'black tea', 'milk', 'beer']
也可以再使用tuple(list)
函式轉回元組:
beverage_list = ['apple juice', 'black tea', 'milk', 'beer']
beverage = tuple(beverage_list)
print(beverage) # ('apple juice', 'black tea', 'milk', 'beer')
使用in
運算符,若該元素在元組中,回傳True
否則False
:
beverage = ("apple juice", "black tea", "milk", "beer")
print("milk" in beverage) # True
print("water" in beverage) # False
使用+
運算符可以得到兩個元組的結合:
beverage = ("apple juice", "black tea", "milk", "beer")
food = ("pasta", "pizza", "burger", "donburi")
meal = beverage + food
print(meal) # ('apple juice', 'black tea', 'milk', 'beer', 'pasta', 'pizza', 'burger', 'donburi')
使用del
可以刪除整個元組;但不能只移除個別元素:
meal = ("apple juice", "black tea", "milk", "beer", "pasta", "pizza", "burger", "donburi")
del meal