如何在 Python 中將元組連線為巢狀元組


如果需要將元組連線至巢狀元組,可以使用“+”運算子。元組是一種不可變的資料型別。這意味著,一旦定義值,便無法透過訪問索引元素來更改。如果我們嘗試更改元素,將導致出錯。它們之所以重要,是因為它們可以確保只讀訪問。

“+”運算子用於加法或連線操作。

以下是同一演示:

示例

現場演示

my_tuple_1 = ( 7, 8, 3, 4, 3, 2),
my_tuple_2 = (9, 6, 8, 2, 1, 4),

print ("The first tuple is : " )
print(my_tuple_1)
print ("The second tuple is : " )
print(my_tuple_2)

my_result = my_tuple_1 + my_tuple_2

print("The tuple after concatenation is : " )
print(my_result)

輸出

The first tuple is :
((7, 8, 3, 4, 3, 2),)
The second tuple is :
((9, 6, 8, 2, 1, 4),)
The tuple after concatenation is :
((7, 8, 3, 4, 3, 2), (9, 6, 8, 2, 1, 4))

說明

  • 定義了兩個元組,並顯示在控制檯上。
  • “+”運算子用於連線值。
  • 此結果分配給變數。
  • 它作為輸出顯示在控制檯上。

更新於: 2021 年 3 月 12 日

1000+ 次觀看

開啟你的職業

完成課程獲得認證

開始
廣告