Python 元組( tuple )它和list列表類似,唯一的差別是元組不能修改。tuple 元組是有序的,一旦定義了元組我們就不能修改它。

一、定義元組

tuple 元組定義使用小括弧 ( ), list 列表使用中括弧 [ ] .

l = [Google, woodman, 1987, 2017]
t1 = (Google, woodman, 1987, 2017, woodman)
t2 = (1, 2, 3, 4)
t3 = (a, b, c)
t4 = (woodman) # 無逗號
print(type(t4)) # t4位str類型
t4 = (woodman,) # 當我們定義元組只有一個值時不要忘記後面的逗號
print(type(t4))
t5 = (woodman, 2017, l, t2) # 元組中可以包含列表和元組
t6 = () # 定義空元組

注意:元組中可以包含 list 列表,元組中 list 列表的值時可變的;定義元組只有一個值時,要在後面加上逗號。

二、訪問元組

元組可以使用下標索引來訪問元組中的值,索引號從0開始。

t = (Google, woodman, 1987, 2017, woodman)

print(t[0]) # 訪問第1個值print(t[2]) # 訪問第3個值

print(t[-1]) # 訪問倒數第1個值

print(t[5]) # 下標索引號越界會拋出 IndexError 異常

三、修改元組

tuple 元組不可以修改

t1 = (Google, woodman)
t2 = (1987, 2017, woodman)
# 我們可以同過元組相加創建一個新元組
t = t1 + t2
print(t)
t1[0] = zhihu # 會拋出TypeError異常,元組不可修改

四、刪除元組

tuple 元組中的元素值是不允許刪除,但我們可以使用del語句來刪除整個元組

t = (Google, woodman, 1987, 2017, woodman)
del t
print(t) # 元組被刪除,拋出NameError異常

五、元組切邊

tuple 元組可以像 list 列表一樣進行切片

l = (Google, woodman, 1987, 2017, a, 1, 2, 3)
print(l[0:2]) # 第1到第2個
print(l[2:15]) # 2到15個,注意如果結束位超過元組長度不會報錯

# 通過步長切片
print(l[0:4:2]) # 每2個數去1個,從第1到第4個
# 輸出 [Google, 1987]
print(l[2::3]) # 從第3個取,每3個取一個,取到結尾
# 輸出 [1987, 1]

# 花式用法
print(l[:3]) # 從開始到tuple第3個元素
print(l[1:]) # 從第二個到tuple結束
print(l[:]) # 獲得一個與l相同的tuple
print(l[-1]) # 取倒數第一個元素
print(l[::-1]) # tuple倒敘
print(l[-3:-1]) # 倒數第三個到第二個
print(l[-4:-1:2]) # 從倒數第4個每2個取一個,到倒數第二個

六、元組的運算

l1 = (1, 2, 3) + (a, b, c) # 連接
print(l1)
l2 = (Hello!,) * 4 # 重複複製
print(l2)
bool1 = a in l1 # 元素是否存在
print(bool1)

七、常用函數

len(tuple) 計算元組元素個數

max(tuple) 返回元組中元素最大值

min(tuple) 返回元組中元素最小值

tuple(list) 將列錶轉換為元組

t = (Google, woodman, 1987, 2017, a, 1, 2, 3)
print(len(t)) # 列表元素個數
t1 = (aA, bss, Ad)
print(max(t1)) # 返回元組中元素最大值,t1元組值必須是同類型
t2 = (6, 2, 3, 5, 1)
print(min(t2)) # 返回元組中元素最小值,t2元組值必須是同類型
l = [1987, 2017, a, 1, 2, 3]
print(tuple(l)) # 將元組轉換為列表

八、常用方法

t = (Google, woodman, 1987, 2017, a, 1, woodman, a, 1)
print(t.count(a)) # 統計元素在元組中的個數
print(t.index(a)) # 返回元素在元組中第一次出現的索引號

推薦閱讀:

相關文章