从 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("元组列表是: ") print(my_input) print("删除重复项后的元组列表是:") print(my_output_list)输出结果
元组列表是: [(45.324, 'Hi Jane, how are you'), (34252.85832, 'Hope you are good'), (45.324, 'You are the best.')] 删除重复项后的元组列表是: [(45.324, 'Hi Jane, how are you'), (34252.85832, 'Hope you are good')]
解释
定义了一个元组列表,并显示在控制台上。
创建一个空集,以及一个空列表。
迭代元组列表,如果它不存在于“集合”中,则将其添加到集合中,以及添加到列表中。
这是显示在控制台上的输出。