共計 619 個字符,預計需要花費 2 分鐘才能閱讀完成。
元組是一種有序的、不可變的數據結構,其使用方法如下:
- 創建元組:使用圓括號 () 來創建一個元組,可以包含任意數量的元素。
my_tuple = (1, 2, 3, 4, 5)
- 訪問元組元素:可以使用索引來訪問元組中的元素,索引從 0 開始。
print(my_tuple[0]) # 輸出:1
- 切片元組:可以使用切片來獲取元組的子集。
print(my_tuple[1:3]) # 輸出:(2, 3)
- 元組的不可變性:元組中的元素不可被修改、刪除或添加。
my_tuple[0] = 10 # 報錯:TypeError: 'tuple' object does not support item assignment
- 遍歷元組:可以使用 for 循環來遍歷元組中的元素。
for item in my_tuple:
print(item)
- 元組的拼接:可以使用 + 運算符來拼接元組。
new_tuple = my_tuple + (6, 7, 8)
print(new_tuple) # 輸出:(1, 2, 3, 4, 5, 6, 7, 8)
- 查找元素:可以使用 in 運算符來檢查元組中是否包含某個元素。
print(3 in my_tuple) # 輸出:True
- 元組的長度和元素個數:可以使用 len() 函數來獲取元組的長度和元素個數。
print(len(my_tuple)) # 輸出:5
總的來說,元組是一種方便存儲和訪問數據的數據結構,尤其適合存儲一組相關的數據項。由于元組是不可變的,可以確保數據的安全性和一致性。
丸趣 TV 網 – 提供最優質的資源集合!
正文完