將 Python 中列表的元組展平為元組


當需要將列表的元組展平為元組時,可以定義一個方法,該方法接收元組作為輸入。

該元組被迭代遍歷,並在此元組上重複呼叫相同的方法,直至獲得結果。

以下是示範說明:

示例

 線上演示

def flatten_tuple(my_tuple):

   if isinstance(my_tuple, tuple) and len(my_tuple) == 2 and not isinstance(my_tuple[0], tuple):
      my_result = [my_tuple]
      return tuple(my_result)

   my_result = []
   for sub in my_tuple:
      my_result += flatten_tuple(sub)
   return tuple(my_result)

my_tuple = ((35, 46), ((67, 70), (8, 11), (10, 111)), (((21, 12), (3, 4))))

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

my_result = flatten_tuple(my_tuple)

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

輸出

The tuple is :
((35, 46), ((67, 70), (8, 11), (10, 111)), ((21, 12), (3, 4)))
The flattened tuple is :
((35, 46), (67, 70), (8, 11), (10, 111), (21, 12), (3, 4))

說明

  • 定義名為“flatten_tuple”的方法,該方法接收元組作為引數。

  • 它檢查元組是否實際上是元組,以及元組的長度是否等於 2。

  • 如果是,則將其作為輸出返回。

  • 接下來,定義一個空列表。

  • 再次迭代遍歷元組,並從展平元組中新增元素到此列表。

  • 將其作為最終輸出返回。

  • 在方法外部定義一個元組的元組,並將其顯示在控制檯上。

  • 透過將這個元組的元組傳遞為引數來呼叫該方法。

  • 輸出顯示在控制檯上。

更新於:2021 年 4 月 19 日

260 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告