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中List的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年9月5日

1K+ 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.