Python 中兩個字串元組的連線


當需要連線兩個字串元組時,可以使用 'zip' 方法和生成器表示式。

zip 方法獲取可迭代物件,將它們聚合到元組中,並將其作為結果返回。

生成器是建立迭代器的簡單方法。它自動實現帶 '__iter__()' 和 '__next__()' 方法的類,並跟蹤內部狀態以及在沒有可以返回的值時引發 'StopIteration' 異常。

以下是演示 -

示例

即時演示

my_tuple_1 = ('Jane', 'Pink', 'El')
my_tuple_2 = ('Will', 'Mark', 'Paul')

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

my_result = tuple(elem_1 + elem_2 for elem_1, elem_2 in zip(my_tuple_1, my_tuple_2))

print("The concatenated tuple is : ")
print(my_result)

輸出

The first tuple is :
('Jane', 'Pink', 'El')
The second tuple is :
('Will', 'Mark', 'Paul')
The concatenated tuple is :
('JaneWill', 'PinkMark', 'ElPaul')

說明

  • 定義了兩個元組列表(字串),並在控制檯上顯示。
  • 迭代這些列表,並使用 'zip' 方法對它們進行壓縮處理。
  • 從兩個元組列表中新增/連線第一個和第二個元素。
  • 然後將其轉換為元組。
  • 此操作分配給變數。
  • 該變數是顯示在控制檯上的輸出。

更新於: 2021 年 3 月 11 日

1 千次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

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