共計 609 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Python 中,tuple(元組)是一個有序、不可變、可以包含不同數據類型的數據結構。它類似于列表(list),但不同之處在于元組的元素不能被修改。tuple 使用圓括號進行定義,并且可以包含任意數量的元素。
以下是 tuple 的常用用法:
- 創建 tuple:
my_tuple = (1, 2, 3)
- 訪問 tuple 元素:
print(my_tuple[0]) # 輸出:1
- 切片操作:
print(my_tuple[1:3]) # 輸出:(2, 3)
- 遍歷 tuple:
for item in my_tuple:
print(item)
- 元素查找:
print(2 in my_tuple) # 輸出:True
- 元素計數:
print(my_tuple.count(2)) # 輸出:1
- 元素索引:
print(my_tuple.index(2)) # 輸出:1
- 解包(unpacking):
x, y, z = my_tuple
- 作為函數的返回值:
def get_coordinates():
return 1, 2, 3
x, y, z = get_coordinates()
需要注意的是,由于元組是不可變的,因此無法對元組進行修改。如果需要對元組中的元素進行修改,可以先將元組轉換為列表,然后進行修改,再轉換回元組。例如:
my_tuple = (1, 2, 3)
my_list = list(my_tuple)
my_list[0] = 4
my_tuple = tuple(my_list) # (4, 2, 3)
丸趣 TV 網 – 提供最優質的資源集合!
正文完