首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

Python Tuple 元組完整入門:建立、存取、不可變性、解包、運算子與巢狀結構詳解

     編輯:更多程式設計知識

元組 是 Python不可變序列,語法用圓括號 ()。與列表類似支援索引、切片、聯集,但建立後無法修改。這特性使其適合作為字典鍵、函數多返回值、固定結構資料載體。

建立元組


# 多元素
t1 = ('physics', 'chemistry', 1997, 2000)
t2 = (1, 2, 3, 4, 5)

# 單元素:必須有逗號
t3 = (50,)        # 元組
not_tuple = (50)  # 整數 50

# 空元組
empty = ()

# 省略括號 (打包)
t4 = "a", "b", "c", "d"
print(type(t4))  # 

# 解包
x, y = 1, 2  # 實際是 tuple 解包

存取與切片


t = ('physics', 'chemistry', 1997, 2000)

print(t[0])       # 'physics'
print(t[1:3])     # ('chemistry', 1997)
print(t[-1])      # 2000
print(t[:2])      # ('physics', 'chemistry')

# 巢狀元組
nested = (1, (2, 3), 4)
print(nested[1][0])  # 2

不可變性與變通


t = (1, 2, 3)
# t[0] = 10  # TypeError: 'tuple' object does not support item assignment

# 變通:建立新元組
t2 = t + (4, 5)        # 聯集
t3 = t * 2             # 重複
t4 = t[:1] + (99,) + t[1:]  # 切片重組
print(t2, t3, t4)

元組運算子

運算子範例結果
+(1,2) + (3,4)(1,2,3,4)
*(1,2) * 3(1,2,1,2,1,2)
in2 in (1,2,3)True
len()len((1,2,3))3
min/maxmin((3,1,2))1
index()(1,2,3).index(2)1
count()(1,2,1).count(1)2

解包與多返回值


# 基本解包
a, b, c = (1, 2, 3)

# 延伸解包 (Py3)
first, *middle, last = (1, 2, 3, 4, 5)
print(first, middle, last)  # 1 [2, 3, 4] 5

# 函數多返回值 (實際回傳元組)
def divmod_custom(a, b):
    return a // b, a % b

q, r = divmod_custom(10, 3)
print(q, r)  # 3 1

# 交換變數
x, y = 10, 20
x, y = y, x  # 建立臨時元組 (y, x) 再解包

刪除元組


t = (1, 2, 3)
del t
# print(t)  # NameError: name 't' is not defined

# 無法刪除單一元素 (不可變)
# del t[0]  # TypeError

索引、切片視覺化


L = ('spam', 'Spam', 'SPAM!')
#  索引:  0       1        2
#  負索引:-3      -2       -1
#  切片 L[1:3] -> ('Spam', 'SPAM!')
#  切片 L[-2:] -> ('Spam', 'SPAM!')

無封閉分隔符:隱式元組


# 逗號才是元組標誌,括號僅為分組/優先序
print('abc', -4.24e93, 18+6.6j, 'xyz')  # 印出 4 個值
x, y = 1, 2  # 右側是隱式元組 (1, 2)

列表 vs 元組 選型指南

場景推薦理由
需修改/增刪元素列表可變
固定結構資料 (座標、RGB、記錄)元組不可變、語意明確、可做 dict key
函數回傳多值元組慣用、解包方便
大量同質資料、頻繁迭代列表記憶體略小、方法豐富
需做字典鍵 / 集合元素元組可雜湊

元組的不可變性不是限制,而是契約:承諾這組資料結構固定,讓程式碼更安全、更易推理。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved