共計 679 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Python 中,元組(tuple)是一個不可變的有序序列,可以存儲多個元素。元組可以通過圓括號 () 來創建,并且可以包含任意類型的元素。
以下是一些常見的元組操作和用法:
- 創建元組:
my_tuple = (1, 2, 3, "a", "b", "c") # 創建一個包含整數和字符串的元組
empty_tuple = () # 創建一個空元組
single_element_tuple = (1,) # 創建只有一個元素的元組
- 訪問元組元素:
print(my_tuple[0]) # 輸出第一個元素:1
print(my_tuple[3:]) # 輸出從第四個元素到最后一個元素:('a', 'b', 'c')
- 元組拼接:
new_tuple = my_tuple + (4, 5, 6) # 將兩個元組拼接在一起
print(new_tuple) # 輸出:(1, 2, 3, 'a', 'b', 'c', 4, 5, 6)
- 元組解包:
a, b, c = (1, 2, 3) # 將元組的每個元素分別賦值給變量 a, b, c
print(a) # 輸出:1
print(b) # 輸出:2
print(c) # 輸出:3
- 元組的遍歷:
for item in my_tuple:
print(item) # 依次輸出元組中的每個元素
- 判斷元素是否在元組中:
print(1 in my_tuple) # 輸出:True
print("d" in my_tuple) # 輸出:False
- 元組的長度:
print(len(my_tuple)) # 輸出:6
由于元組是不可變的,所以無法對元組中的元素進行修改。但是,如果元組中的元素是可變的對象(如列表),則可以修改可變對象的內容。
希望以上解答能對您有所幫助!
丸趣 TV 網 – 提供最優質的資源集合!
正文完