元組

文武双全·墨海纵横發表於2024-07-25

Python 的元組(tuple,簡寫為tup)與列表類似,不同之處在於元組的元素不能修改。

元組使用小括號​()​,列表使用方括號​[]​。

建立元組

# 建立一個空原元組
empty_tup = ()
print(empty_tup)
# 輸出:()
# 建立一個包含多個元素的元組
number = (1, 2, 3,4 ,5)
print(number)
# 輸出:(1, 2, 3, 4, 5)
# 單個元素的元組
singleton = (1,)
print(singleton)
# 輸出:(1,) 

訪問元組元素

print(number[0])
# 輸出: 1

# 元組切片
print(number[1:3])#獲取第2到第3個元素(不包括索引3)
# 輸出:(2, 3)

# 不可變性
number = (1,2,3)
# number[1] = 3
# 輸出異常: TypeError
#   File "f:\rgzn\Python\tuple_demo.py", line 25, in <module>
#     number[1] = 3
# TypeError: 'tuple' object does not support item assignment

多級元組操作示例


# 建立一個多級元組
teacher = (
    ('Alice',20, ('Math',95),('Tom',88)),
    ('Bob',22,('Marth',82),('Science',92)),
    ('Charlie',14,('Marth',90),('Science',85))
)
# 訪問第一老師的名字
print(teacher[0][0])
# 輸出 Alice
# 訪問第二老師的學習成績
print(teacher[1][2][1])
# 輸出 82
# 訪問Bob 的所有資料
print(teacher[1])
# 輸出('Bob', 22, ('Marth', 82), ('Science', 92))
# 訪問Charlie的科學成績
print(teacher[2][3][1])
# 輸出85

遍歷多級元組

for student in teacher:
    name = student[0]
    age = student[1]
    math_score = student[2][1]
    print(f'{name}今年{age}歲了,他數學考了{math_score}分,科學考了{student[3][1]}分')
# 輸出
# Alice今年20歲了,他數學考了95分,科學考了88分
# Bob今年22歲了,他數學考了82分,科學考了92分
# Charlie今年14歲了,他數學考了90分,科學考了85分

修改多級元組

# 注意: 我們無法直接修改元組,但是可以建立新的元組
update_teacher = []
for student in teacher:
    if student[0] == 'Charlie':
        new_teacher = (student[0],student[1],(student[2][0],student[2][1]+5),student[3])
        update_teacher.append(new_teacher)
    else:
        update_teacher.append(student)
# list 再轉化成 tuple 
update_teacher =  tuple(update_teacher)
# 列印結果
print(update_teacher)
# 輸出: (('Alice', 20, ('Math', 95), ('Tom', 88)), ('Bob', 22, ('Marth', 82), ('Science', 92)), ('Charlie', 14, ('Marth', 95), ('Science', 85)))

# 修改元組的另外一種方式
# 在Python中,元組(tuple)是不可變的,這意味著一旦你建立了一個元組,你就不能更改它裡面的元素。
# 但是,如果元組中的元素是可變型別(比如列表list),你可以修改這個可變型別元素的內容,而不會違反元組的不可變性。
# 這是因為元組的不可變性是指你不能更改元組中的元素引用(即你不能將元組中的一個元素替換為另一個元素),而不是指你不能更改元素本身(如果它是可變的)。
# 建立一個帶有 list的 元組
my_tuple = (1,2,3,[4,5],'a','b')
# 如果直接修改會報錯TypeError
# my_tuple[3] = [1,2,3]
print(id(my_tuple)) 
# 輸出:2039667320544
# 可以直接修改list裡的值
my_tuple[3][0] = 'a'
my_tuple[3][1] = 'b'
# my_tuple[3][2] = 'c' # 這種會報錯 IndexError  陣列越界
my_tuple[3].append('c') # 這種可以成功
print(my_tuple)
# 輸出:(('Alice', 20, ('Math', 95), ('Tom', 88)), ('Bob', 22, ('Marth', 82), ('Science', 92)), ('Charlie', 14, ('Marth', 95), ('Science', 85)))
print(id(my_tuple))
# 輸出:2039667320544

# 輸出:(1, 2, 3, ['a', 'b', 'c'], 'a', 'b')
# 總結: 本身元組無法修改的,我們可以透過新建list 獲取 元組的值進行修改 再組裝成元組方式進行元組修改
#       如果元組中具備可修改型別的資料,可以對可變型別進行修改,注意不可直接賦值修改,需要到可修改的內容裡修改
#       上述例子中 list 可以透過下標賦值, 可以透過append()增加元素
#       如果修改元組的list資料 修改前和修改後的記憶體地址一致

元組的內建函式

my_tuple = (1,2,3,4,5,6,7,8,9)
# 返回元組的長度
print(len(my_tuple))
# 輸出9
# 返回元組的最大值 - 元組內的資料必須同型別才可以
print(max(my_tuple))
# 輸出9
# 返回元組的最小值 - 元組內的資料必須同型別才可以
print(min(my_tuple))
# 輸出1
# 比較兩個元組
my_tuple = (1,2,3,4,5,6,7,8,9)
my_tuple2= (1,2,3,4,5,6,7,8,9)
my_tuple3= (1,2,3,4,5,6,7,8,'9')
# operator 在3.10中會報錯 後面改成 == 可以
# print(operator(my_tuple,my_tuple2))

print(my_tuple == my_tuple2)
# 輸出True
print(my_tuple == my_tuple3)
# 輸出False

元組的內建函式

# 元組重新賦值後 記憶體地址改變
my_tuple4= (1,2,3,4,5,6,7,8,9)
print(id(my_tuple4))
# 輸出:2039667116848
my_tuple4= (1,2,3,4,5,6,7,8,'9')
print(id(my_tuple4))
# 輸出:2039667124240

兩個元組資料的操作

比較
tuple1 = (1, 2, 3)  
tuple2 = (1, 2, 3)  
tuple3 = (1, 2, 4)  
  
print(tuple1 == tuple2)  # 輸出: True  
print(tuple1 != tuple3)  # 輸出: True  
print(tuple1 < tuple3)   # 輸出: True,因為第一個不同的元素1 < 4
合併
tuple1 = (1, 2, 3)  
tuple2 = ('a', 'b', 'c')  
  
# 使用 + 運算子合並  
merged_tuple = tuple1 + tuple2  
print(merged_tuple)  # 輸出: (1, 2, 3, 'a', 'b', 'c')  
  
# 使用 * 運算子重複元組(這不是合併,但展示了另一種操作)  
repeated_tuple = tuple1 * 2  
print(repeated_tuple)  # 輸出: (1, 2, 3, 1, 2, 3)
遍歷
tuple1 = (1, 2, 3)  
tuple2 = ('a', 'b', 'c')  
  
# 分別遍歷  
for item in tuple1:  
    print(item)  
  
for item in tuple2:  
    print(item)  
  
# 同時遍歷(使用zip)  
for item1, item2 in zip(tuple1, tuple2):  
    print(item1, item2)
使用元組作為字典的鍵或者結合的元素
my_dict = {(1, 2): 'a', (3, 4): 'b'}  
print(my_dict[(1, 2)])  # 輸出: a  
  
my_set = {(1, 2), (3, 4), (5, 6)}  
print(my_set)  # 輸出可能不同,因為集合是無序的
轉換和對映
tuple1 = (1, 2, 3, 4, 5)  
  
# 建立一個新元組,其元素是原始元組元素的平方  
squared_tuple = tuple(x**2 for x in tuple1)  
print(squared_tuple)  # 輸出: (1, 4, 9, 16, 25)

相關文章