iT邦幫忙

2022 iThome 鐵人賽

DAY 6
0
  • 建立元組
  • 元組長度
  • 訪問元組元素
  • 片取元組
  • 元組轉串列
  • 確認元組是否有某一元素
  • 結合元組
  • 刪除元組

這篇文章是閱讀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

上一篇
【Day 5】串列
下一篇
【Day 7】集合
系列文
從前端角度看30天學Python30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言