📜  Python|从列表中获取重复的元组

📅  最后修改于: 2022-05-13 01:55:45.826000             🧑  作者: Mango

Python|从列表中获取重复的元组

有时,在处理记录时,我们可能会遇到提取那些多次出现的记录的问题。这种应用可以发生在Web开发领域。让我们讨论可以执行此任务的某些方式。

方法 #1:使用列表理解 + set() + count()
可以应用的初始方法是我们可以迭代每个元组并使用count()检查它在列表中的计数,如果大于一,我们可以添加到列表中。要删除多个添加,我们可以使用set()将结果转换为集合。

# Python3 code to demonstrate working of
# Get duplicate tuples from list
# Using list comprehension + set() + count()
  
# initialize list
test_list = [(3, 4), (4, 5), (3, 4), 
             (3, 4), (4, 5), (6, 7)]
  
# printing original list 
print("The original list : " + str(test_list))
  
# Get duplicate tuples from list
# Using list comprehension + set() + count()
res = list(set([ele for ele in test_list
            if test_list.count(ele) > 1]))
  
# printing result
print("All the duplicates from list are : " + str(res))
输出 :
The original list : [(3, 4), (4, 5), (3, 4), (3, 4), (4, 5), (6, 7)]
All the duplicates from list are : [(4, 5), (3, 4)]

方法#2:使用Counter() + items() + list comprehension
上述功能的组合也可用于执行此特定任务。在这种情况下,我们只是使用Counter()作为字典来获取每个元素出现的计数,然后提取所有值大于 1 的元素。

# Python3 code to demonstrate working of
# Get duplicate tuples from list
# Using list comprehension + Counter() + items()
from collections import Counter
  
# initialize list
test_list = [(3, 4), (4, 5), (3, 4), 
             (3, 4), (4, 5), (6, 7)]
  
# printing original list 
print("The original list : " + str(test_list))
  
# Get duplicate tuples from list
# Using list comprehension + Counter() + items()
res = [ele for ele, count in Counter(test_list).items()
                                          if count > 1]
  
# printing result
print("All the duplicates from list are : " + str(res))
输出 :
The original list : [(3, 4), (4, 5), (3, 4), (3, 4), (4, 5), (6, 7)]
All the duplicates from list are : [(4, 5), (3, 4)]