一、定義和創建元組
在Python中,元組是一個不可變的序列。它由多個逗號分隔的值組成,可以包含任何類型的值,包括數字、字符串、列表、元組等。元組使用小括號進行創建,其中可以省略小括號。例如:
# 創建一個空元組
empty_tuple = ()
empty_tuple = tuple()
# 創建一個包含多個值的元組
my_tuple = (1, 'hello', ['a', 'b', 'c'], ('x', 'y', 'z'))
my_tuple = 1, 'hello', ['a', 'b', 'c'], ('x', 'y', 'z')
二、訪問和切片元組
元組是有序的,可以通過下標(索引)訪問其中的值,下標從0開始計數。和列表一樣,可以使用切片(slicing)操作獲取元組的子集,語法格式為[start:stop:step]。
my_tuple = (1, 'hello', ['a', 'b', 'c'], ('x', 'y', 'z'))
print(my_tuple[1]) # 輸出:hello
print(my_tuple[2][1]) # 輸出:b
print(my_tuple[1:3]) # 輸出:('hello', ['a', 'b', 'c'])
print(my_tuple[::2]) # 輸出:(1, ['a', 'b', 'c'])
三、元組的基本操作
1. 元組的長度
和列表一樣,可以使用內建函數len()獲取元組的長度。
my_tuple = (1, 'hello', ['a', 'b', 'c'], ('x', 'y', 'z'))
print(len(my_tuple)) # 輸出:4
2. 元組的重複
和字符串一樣,可以使用運算符*對元組進行重複操作。
my_tuple = (1, 'hello', ['a', 'b', 'c'], ('x', 'y', 'z'))
new_tuple = my_tuple * 3
print(new_tuple) # 輸出:(1, 'hello', ['a', 'b', 'c'], ('x', 'y', 'z'), 1, 'hello', ['a', 'b', 'c'], ('x', 'y', 'z'), 1, 'hello', ['a', 'b', 'c'], ('x', 'y', 'z'))
3. 元組的連接
可以使用運算符+對兩個元組進行連接操作。
my_tuple1 = (1, 2, 3)
my_tuple2 = ('a', 'b', 'c')
new_tuple = my_tuple1 + my_tuple2
print(new_tuple) # 輸出:(1, 2, 3, 'a', 'b', 'c')
四、元組的遍歷
和列表一樣,可以使用for循環和while循環遍曆元組。
my_tuple = (1, 'hello', ['a', 'b', 'c'], ('x', 'y', 'z'))
for i in my_tuple:
print(i)
i = 0
while i < len(my_tuple):
print(my_tuple[i])
i += 1
五、元組的不可變性
元組是不可變的,一旦創建就不能對其中的值進行修改、刪除或添加。如果需要對元組進行修改操作,可以先將元組轉換為列表,再進行修改。
my_tuple = (1, 'hello', ['a', 'b', 'c'], ('x', 'y', 'z'))
# 修改元組中列表的值
my_tuple[2][0] = 'd'
print(my_tuple) # 輸出:(1, 'hello', ['d', 'b', 'c'], ('x', 'y', 'z'))
# 將元組轉換為列表,修改值後再轉換為元組
my_list = list(my_tuple)
my_list[1] = 'world'
my_tuple = tuple(my_list)
print(my_tuple) # 輸出:(1, 'world', ['d', 'b', 'c'], ('x', 'y', 'z'))
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/243494.html