從 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 中。
- 這是顯示在控制檯上的輸出。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP