Python – 將元組列表中後部元素連線起來


當需要連線元組列表的後部元素時,可以使用列表解析和“join”方法。

示例

以下是對此進行演示 −

my_tuple = [(13, 42, "Will"), (48, "is a"), ("good boy", )]

print("The tuple is : " )
print(my_tuple)

my_result = " ".join([sub[-1] for sub in my_tuple])

print("The result is : " )
print(my_result)

輸出

The list is :
[(13, 42, 'Will'), (48, 'is a'), ('good boy',)]
The concatenated list is :
Will is a good boy

說明

  • 定義了一個元組列表,並在控制檯上顯示。

  • 使用列表解析和“join”方法來獲取元組列表中的最後一個元素。

  • 此結果被分配給一個變數。

  • 這是在控制檯上顯示的輸出。

更新時間:2021-09-08

182次瀏覽

開啟您的 事業

完成課程獲取認證

開始學習
廣告