Python 中元組的連線運算子如何工作?


元組是 Python 物件的集合,這些物件由逗號分隔,是有序且不可變的。元組與列表一樣,都是序列。元組和列表之間的區別在於,元組與列表不同,元組不能更改,元組使用圓括號,而列表使用方括號。

tup=('tutorials', 'point', 2022,True)
print(tup)

如果您執行上述程式碼段,將產生以下輸出:

('tutorials', 'point', 2022, True)

在本文中,我們將瞭解連線運算子在 Python 中如何作用於元組。

元組的連線操作

Python 中的元組連線是指將兩個或多個元組連線起來形成單個元組。有多種方法可以執行兩個元組的連線。下面討論了其中兩種方法。

  • 使用“+”運算子。
  • 使用 sum() 函式。

使用“+”運算子

當需要連線多個元組時,可以使用“+”運算子。元組是一種不可變資料型別。這意味著一旦定義了值,就無法透過訪問其索引元素來更改它。如果嘗試更改元素,我們會得到一個錯誤。它們至關重要,因為它們保證了只讀訪問。

“+”運算子可用於連線文字或新增數值。

示例

以下示例演示瞭如何使用“+”運算子連線元組。

tuple_1 = (11, 14, 0, 78, 33, 11)
tuple_2 = (10, 78, 0, 56, 8, 34)
print("The first tuple is : ")
print(tuple_1)
print("The second tuple is : ")
print(tuple_2)
result = tuple_1 + tuple_2
print("The tuple after concatenation is : " )
print(result)

輸出

以上程式碼的輸出如下:

The first tuple is : 
(11, 14, 0, 78, 33, 11)
The second tuple is : 
(10, 78, 0, 56, 8, 34)
The tuple after concatenation is : 
(11, 14, 0, 78, 33, 11, 10, 78, 0, 56, 8, 34)

使用 sum() 函式。

還有另一種解決此問題的方法,我們使用 sum() 函式連線元組。sum() 函式以兩個元組作為引數,並返回一個單個元組,該元組是這兩個元組的連線。

示例

在以下示例程式碼中,我們使用 sum() 函式連線兩個元組。

tuple_1 = (11, 14, 0, 78, 33, 11)
tuple_2 = (10, 78, 0, 56, 8, 34)
print("The first tuple is : ")
print(tuple_1)
print("The second tuple is : ")
print(tuple_2)
result = sum((tuple_1, tuple_2), ())
print("The tuple after concatenation is : " )
print(result)

輸出

以上程式碼將產生以下輸出。

The first tuple is : 
(11, 14, 0, 78, 33, 11)
The second tuple is : 
(10, 78, 0, 56, 8, 34)
The tuple after concatenation is : 
(11, 14, 0, 78, 33, 11, 10, 78, 0, 56, 8, 34)

使用 list() 和 extend() 方法

Python 中列表的 extends() 方法用於新增兩個列表。要使用這些方法連線兩個元組

  • 使用 list() 方法將元組轉換為列表。
  • 使用 extend() 方法新增這兩個列表。

示例

以下是一個使用 list() 和 extend() 方法連線兩個陣列的示例:

tuple1 = ('JavaFX', 'OpenCV','CoffeeScript')
tuple2 = ('Hadoop', 'Spark')

print("Contents of tuple1 : " + str(tuple1))
print("Contents of tuple2 : " + str(tuple2))

list1=list(tuple1)
list1.extend(tuple2)
print("Result : " + str(list1))

輸出

Contents of tuple1 : ('JavaFX', 'OpenCV', 'CoffeeScript')
Contents of tuple2 : ('Hadoop', 'Spark')Result : ['JavaFX', 'OpenCV', 'CoffeeScript', 'Hadoop', 'Spark']

更新於: 2022-09-05

1K+ 次檢視

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.