Python - 更新元組



在 Python 中更新元組

在 Python 中,元組 是一個不可變的序列,這意味著一旦建立了一個元組,其元素就不能更改、新增或刪除。

要在 Python 中更新元組,您可以組合各種操作來建立一個新元組。例如,您可以連線元組、切片它們或使用元組解包來達到預期的結果。這通常涉及將元組轉換為列表,進行必要的修改,然後將其轉換回元組。

使用連線運算子更新元組

Python 中的連線運算子,用 + 表示,用於將兩個序列(例如字串、列表或元組)連線成一個序列。當應用於元組時,連線運算子將兩個(或多個)元組的元素連線起來,建立一個包含兩個元組所有元素的新元組。

我們可以使用連線運算子更新元組,方法是建立一個包含原始元組和附加元素的新元組。

由於元組是不可變的,因此使用連線運算子更新元組不會修改原始元組,而是建立一個包含所需元素的新元組。

示例

在以下示例中,我們使用“+”運算子連線“T1”和“T2”來建立一個新元組:

# Original tuple
T1 = (10, 20, 30, 40)
# Tuple to be concatenated
T2 = ('one', 'two', 'three', 'four')
# Updating the tuple using the concatenation operator
T1 = T1 + T2
print(T1)

它將產生以下輸出:

(10, 20, 30, 40, 'one', 'two', 'three', 'four')

使用切片更新元組

Python 中的切片用於透過指定索引範圍來提取序列(例如列表、元組或字串)的一部分。切片的語法如下:

sequence[start:stop:step]

其中,

  • start 是切片開始的索引(包含)。
  • stop 是切片結束的索引(不包含)。
  • step 是切片中元素之間的間隔(可選)。

我們可以使用切片更新元組,方法是建立一個包含原始元組的切片和新元素的新元組。

示例

在這個例子中,我們透過將其切成兩部分並在切片之間插入新元素來更新元組:

# Original tuple
T1 = (37, 14, 95, 40)
# Elements to be added
new_elements = ('green', 'blue', 'red', 'pink')
# Extracting slices of the original tuple
# Elements before index 2
part1 = T1[:2]  
# Elements from index 2 onward
part2 = T1[2:]  
# Create a new tuple 
updated_tuple = part1 + new_elements + part2
# Printing the updated tuple
print("Original Tuple:", T1)
print("Updated Tuple:", updated_tuple)

以下是上述程式碼的輸出:

Original Tuple: (37, 14, 95, 40)
Updated Tuple: (37, 14, 'green', 'blue', 'red', 'pink', 95, 40)

使用列表推導式更新元組

Python中的列表推導式是一種簡潔建立列表的方式。它允許你透過對現有可迭代物件(例如列表、元組或字串)中的每個專案應用表示式來生成新的列表,還可以選擇性地包含條件來過濾元素。

由於元組是不可變的,更新元組需要將其轉換為列表,使用列表推導式進行所需的更改,然後將其轉換回元組。

示例

在下面的示例中,我們透過首先將元組轉換為列表,並使用列表推導式為每個元素新增100來更新元組。然後我們將列表轉換回元組以獲取更新後的元組 -

# Original tuple
T1 = (10, 20, 30, 40)
# Converting the tuple to a list
list_T1 = list(T1)
# Using list comprehension 
updated_list = [item + 100 for item in list_T1]
# Converting the updated list back to a tuple
updated_tuple = tuple(updated_list)
# Printing the updated tuple
print("Original Tuple:", T1)
print("Updated Tuple:", updated_tuple)

上述程式碼的輸出如下 -

Original Tuple: (10, 20, 30, 40)
Updated Tuple: (110, 120, 130, 140)

使用append()函式更新元組

append()函式用於向列表末尾新增單個元素。但是,由於元組是不可變的,因此append()函式不能直接用於更新元組。

要使用append()函式更新元組,我們需要首先將元組轉換為列表,然後使用append()新增元素,最後將列表轉換回元組。

示例

在下面的示例中,我們首先將原始元組“T1”轉換為列表“list_T1”。然後我們使用迴圈遍歷新元素,並使用append()函式將每個元素附加到列表中。最後,我們將更新後的列表轉換回元組以獲取更新後的元組 -

# Original tuple
T1 = (10, 20, 30, 40)
# Convert tuple to list
list_T1 = list(T1)
# Elements to be added
new_elements = [50, 60, 70]
# Updating the list using append()
for element in new_elements:
    list_T1.append(element)
# Converting list back to tuple
updated_tuple = tuple(list_T1)
# Printing the updated tuple
print("Original Tuple:", T1)
print("Updated Tuple:", updated_tuple)

我們得到如下所示的輸出 -

Original Tuple: (10, 20, 30, 40)
Updated Tuple: (10, 20, 30, 40, 50, 60, 70)
廣告