用 Python 從字串和列表建立元組


如果需要根據一條字串和一個列表建立元組,可以使用元組方法。

可以使用列表儲存異構值(即任何資料型別的資料,如整數、浮點數、字串等)。

以下對上述情況進行了演示 −

示例

即時演示

my_list_1 = ['Hey', 'there', 'How', 'are', 'you']
my_list_2 = 'Jane'

print("The first list is :")
print(my_list_1)

print("The string is :")
print(my_list_2)

my_result = tuple(my_list_1 + [my_list_2])
print("The aggregated tuple is : ")
print(my_result)

輸出

The first list is :
['Hey', 'there', 'How', 'are', 'you']
The string list is :
Jane
The aggregated tuple is :
('Hey', 'there', 'How', 'are', 'you', 'Jane')

說明

  • 建立了一個列表並顯示在控制檯上。
  • 定義另一個字串。
  • 使用元組和“[]”聚合列表和字串。
  • 最終輸出顯示在控制檯上。

更新於: 11-Mar-2021

142 次瀏覽

職業生涯快步起步

完成課程獲得認證

開始
廣告
© . All rights reserved.