Python | 從列表中移除空元組


如果需要從元組列表中移除空元組,可以使用一個簡單的迴圈。

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

元組列表基本上包含一個列表中封裝的元組。

以下是一個演示,涉及相同的內容 -

示例

 線上演示

def remove_empty(my_tuple):
   my_tuple = [t for t in my_tuple if t]
   return my_tuple
my_tuple = [(), (), (''), (" " , " "), (45, 67, 35, 66, 74, 89, 100) , 'jane']
print("The tuple is : ")
print(my_tuple)
print("The method to remove empty tuples is being called...")
my_result = remove_empty(my_tuple)
print("The list of tuple after remvoing empty tuples is : ")
print(my_result)

輸出

The tuple is :
[(), (), '', (' ', ' '), (45, 67, 35, 66, 74, 89, 100), 'jane']
The method to remove empty tuples is being called...
The list of tuple after remvoing empty tuples is :
[(' ', ' '), (45, 67, 35, 66, 74, 89, 100), 'jane']

說明

  • 定義了一個名為“remove_empty”的方法,該方法將元組列表作為引數。
  • 它遍歷元組,僅在它們非空時返回值。
  • 定義了一個元組列表,並在控制檯中顯示該列表。
  • 透過傳遞此元組列表呼叫該方法。
  • 此操作的資料分配給一個變數。
  • 然後它在控制檯中顯示為輸出。

更新於: 11-3-2021

855 次瀏覽

開啟你的 職業生涯

完成課程以獲得認證

開始操作
廣告