📜  在集合列表中查找重复集合的Python程序

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

在集合列表中查找重复集合的Python程序

给定一个集合列表,任务是编写一个Python程序来查找重复的集合。

方法 #1:使用Counter() + count() + freezeset() + 循环

在这种情况下,所有集合都通过使用 Counter() 将它们转换为frozenset() [以获得可散列类型] 到频率来进行散列。然后 count() 用于从创建的频率计数器中获取所有当前集合的计数。

Python3
# Python3 code to demonstrate working of
# Duplicate sets in list of sets
# Using Counter() + count() + frozenset() + loop
from collections import Counter
  
# initializing list
test_list = [{4, 5, 6, 1}, {6, 4, 1, 5}, {1, 3, 4, 3}, 
             {1, 4, 3}, {7, 8, 9}]
               
# printing original list
print("The original list is : " + str(test_list))
  
# getting frequency using Counter()
freqs = Counter(frozenset(sub) for sub in test_list)
  
res = []
for key, val in freqs.items():
      
    # if frequency greater than 1, set is appended 
    # [duplicate]
    if val > 1 :
        res.append(key)
  
# printing result
print("Duplicate sets list : " + str(res))


Python3
# Python3 code to demonstrate working of
# Duplicate sets in list of sets
# Using list comprehension + Counter()
from collections import Counter
  
# initializing list
test_list = [{4, 5, 6, 1}, {6, 4, 1, 5}, {1, 3, 4, 3}, {1, 4, 3}, {7, 8, 9}]
               
# printing original list
print("The original list is : " + str(test_list))
  
# getting frequency using Counter()
freqs = Counter(frozenset(sub) for sub in test_list)
  
# list comprehension provides shorthand solution
res = [key for key, val in freqs.items() if val > 1]
  
# printing result
print("Duplicate sets list : " + str(res))


输出:

方法 #2:使用列表理解+ Counter()

在这里,我们执行类似的任务,唯一的区别是使用列表理解作为一个线性来基于频率字典提取重复项。

蟒蛇3

# Python3 code to demonstrate working of
# Duplicate sets in list of sets
# Using list comprehension + Counter()
from collections import Counter
  
# initializing list
test_list = [{4, 5, 6, 1}, {6, 4, 1, 5}, {1, 3, 4, 3}, {1, 4, 3}, {7, 8, 9}]
               
# printing original list
print("The original list is : " + str(test_list))
  
# getting frequency using Counter()
freqs = Counter(frozenset(sub) for sub in test_list)
  
# list comprehension provides shorthand solution
res = [key for key, val in freqs.items() if val > 1]
  
# printing result
print("Duplicate sets list : " + str(res))

输出: