Python - 多组对称差
集合组之间的对称差异是属于任何一个集合但不存在于任何其他集合中的元素。给定一个集合列表,任务是编写一个Python程序来获得相同的对称差异。
Input : test_list = [{5, 3, 2, 6, 1}, {7, 5, 3, 8, 2}, {9, 3}, {0, 3, 6, 7}]
Output : {8, 1, 9, 0}
Explanation : 8, 1, 9, 0 occur just 1 time over whole container.
Input : test_list = [{5, 3, 2, 6, 1}, {7, 5, 3, 8, 2}, {9, 3}]
Output : {8, 1, 9}
Explanation : 8, 1, 9 occur just 1 time over whole container.
方法#1:使用Counter() + chain.from_iterable()
此方法用于通过展平来检查所有具有 1 作为频率总体集的元素。 Counter() 提取频率,然后可以提取所有计数为 1 的元素。
Python3
# Python3 code to demonstrate working of
# Symmetric Difference of Multiple sets
# Using Counter() + chain.from_iterable()
from collections import Counter
from itertools import chain
# initializing list
test_list = [{5, 3, 2, 6, 1},
{7, 5, 3, 8, 2},
{9, 3},
{0, 3, 6, 7}]
# printing original list
print("The original list is : " + str(test_list))
# getting frequencies using Counter()
# from_iterable() flattens the list
freq = Counter(chain.from_iterable(test_list))
# getting frequency count 1
res = {idx for idx in freq if freq[idx] == 1}
# printing result
print("Symmetric difference of multiple list : " + str(res))
Python3
# Python3 code to demonstrate working of
# Symmetric Difference of Multiple sets
# Using Counter() + chain.from_iterable() + items()
from collections import Counter
from itertools import chain
# initializing list
test_list = [{5, 3, 2, 6, 1},
{7, 5, 3, 8, 2},
{9, 3}, {0, 3, 6, 7}]
# printing original list
print("The original list is : " + str(test_list))
# clubbing operations using items() to get items
res = {key for key, val in Counter(chain.
from_iterable(test_list)).
items() if val == 1}
# printing result
print("Symmetric difference of multiple list : " + str(res))
输出:
The original list is : [{1, 2, 3, 5, 6}, {2, 3, 5, 7, 8}, {9, 3}, {0, 3, 6, 7}]
Symmetric difference of multiple list : {8, 1, 9, 0}
方法#2:使用 Counter() + chain.from_iterable() + items()
与上述方法类似,唯一的区别是通过使用 items() 提取键和值在单步执行。
蟒蛇3
# Python3 code to demonstrate working of
# Symmetric Difference of Multiple sets
# Using Counter() + chain.from_iterable() + items()
from collections import Counter
from itertools import chain
# initializing list
test_list = [{5, 3, 2, 6, 1},
{7, 5, 3, 8, 2},
{9, 3}, {0, 3, 6, 7}]
# printing original list
print("The original list is : " + str(test_list))
# clubbing operations using items() to get items
res = {key for key, val in Counter(chain.
from_iterable(test_list)).
items() if val == 1}
# printing result
print("Symmetric difference of multiple list : " + str(res))
输出:
The original list is : [{1, 2, 3, 5, 6}, {2, 3, 5, 7, 8}, {9, 3}, {0, 3, 6, 7}]
Symmetric difference of multiple list : {8, 1, 9, 0}