從 Python 中的給定元組列表中移除具有重複第一個值的元組


當需要從給定的元組列表集移除具有重複第一個值的元組時,可以使用一個簡單的 'for' 迴圈,以及 'add' 和 'append' 方法。

以下是演示同樣內容的內容 −

示例

線上演示

my_input = [(45.324, 'Hi Jane, how are you'),(34252.85832, 'Hope you are good'),(45.324, 'You are the best.')]
visited_data = set()

my_output_list = []
for a, b in my_input:
   if not a in visited_data:
      visited_data.add(a)
      my_output_list.append((a, b))

print("The list of tuple is : ")
print(my_input)
print("The list of tuple after removing duplicates is :")
print(my_output_list)

輸出

The list of tuple is :
[(45.324, 'Hi Jane, how are you'), (34252.85832, 'Hope you are good'), (45.324, 'You are the best.')]
The list of tuple after removing duplicates is :
[(45.324, 'Hi Jane, how are you'), (34252.85832, 'Hope you are good')]

說明

  • 定義了一個元組列表,並顯示在控制檯上。
  • 建立了一個空集合和一個空列表。
  • 迭代元組列表,如果 'set' 中不存在,則將其新增到 set 和 list 中。
  • 這是顯示在控制檯上的輸出。

更新於: 13-Mar-2021

535 次檢視

開啟你的職業生涯

完成課程獲得認證

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