如何创建一组新的所有元素,这些元素仅属于多个集合中的一个?
How to create a new set of all elements that are in only one of multiple sets?
我需要代码:
- 扫描四个不同集合的所有元素
- 将仅在一组中唯一出现的值放入新集中,而将其他值放入新集中
示例:
一个{1,2,3,4,5}
B{1,2,3,4,6}
C{1,3,4,7}
D{1,8,9}
集合 E 看起来像:{5,6,7,8,9}
合并所有集合(允许重复),计算元素数量,然后取只出现一次的元素怎么样?
import itertools
import collections
A = {1,2,3,4,5}
B = {1,2,3,4,6}
C = {1,3,4,7}
D = {1,8,9}
cnt = collections.Counter(itertools.chain(A, B, C, D))
E = {k for k, v in cnt.items() if v == 1}
print(E) # {5, 6, 7, 8, 9}
如果你有点舍不得导入模块,下面是等价的:
A = {1,2,3,4,5}
B = {1,2,3,4,6}
C = {1,3,4,7}
D = {1,8,9}
cnt = {} # prepare an empty list
for s in [A, B, C, D]: # loop over sets
for x in s: # for each element in set s
cnt[x] = cnt.get(x, 0) + 1 # increment the counter
E = set(k for k, v in cnt.items() if v == 1) # set consisting of singleton elements
print(E) # {5, 6, 7, 8, 9}
执行此操作的一种方法是将所有集合解压缩到一个列表中。然后遍历他们的联合,得到他们的计数:
a = {1,2,3,4,5}
b = {1,2,3,4,6}
c = {1,3,4,7}
d = {1,8,9}
joined = [*a, *b, *c, *d]
result = {i for i in set.union(a, b, c, d) if not joined.count(i) - 1}
{5, 6, 7, 8, 9}
如果将 collections.Counter
用于 joined
和 itertools.chain
:
,可以提高效率
from collections import Counter
result = {i for i, c in Counter(chain(a, b, c, d)).items() if c == 1}
您可以在集合上循环并积累一个唯一且通用的集合来提取所需的结果:
A={1,2,3,4,5}
B={1,2,3,4,6}
C={1,3,4,7}
D={1,8,9}
unique,common = set(),set()
for S in (A,B,C,D):
unique = (unique|S) - (S&common) # add set, remove duplicates
common |= S # track seen items
print(unique)
{5, 6, 7, 8, 9}
我需要代码:
- 扫描四个不同集合的所有元素
- 将仅在一组中唯一出现的值放入新集中,而将其他值放入新集中
示例:
一个{1,2,3,4,5}
B{1,2,3,4,6}
C{1,3,4,7}
D{1,8,9}
集合 E 看起来像:{5,6,7,8,9}
合并所有集合(允许重复),计算元素数量,然后取只出现一次的元素怎么样?
import itertools
import collections
A = {1,2,3,4,5}
B = {1,2,3,4,6}
C = {1,3,4,7}
D = {1,8,9}
cnt = collections.Counter(itertools.chain(A, B, C, D))
E = {k for k, v in cnt.items() if v == 1}
print(E) # {5, 6, 7, 8, 9}
如果你有点舍不得导入模块,下面是等价的:
A = {1,2,3,4,5}
B = {1,2,3,4,6}
C = {1,3,4,7}
D = {1,8,9}
cnt = {} # prepare an empty list
for s in [A, B, C, D]: # loop over sets
for x in s: # for each element in set s
cnt[x] = cnt.get(x, 0) + 1 # increment the counter
E = set(k for k, v in cnt.items() if v == 1) # set consisting of singleton elements
print(E) # {5, 6, 7, 8, 9}
执行此操作的一种方法是将所有集合解压缩到一个列表中。然后遍历他们的联合,得到他们的计数:
a = {1,2,3,4,5}
b = {1,2,3,4,6}
c = {1,3,4,7}
d = {1,8,9}
joined = [*a, *b, *c, *d]
result = {i for i in set.union(a, b, c, d) if not joined.count(i) - 1}
{5, 6, 7, 8, 9}
如果将 collections.Counter
用于 joined
和 itertools.chain
:
from collections import Counter
result = {i for i, c in Counter(chain(a, b, c, d)).items() if c == 1}
您可以在集合上循环并积累一个唯一且通用的集合来提取所需的结果:
A={1,2,3,4,5}
B={1,2,3,4,6}
C={1,3,4,7}
D={1,8,9}
unique,common = set(),set()
for S in (A,B,C,D):
unique = (unique|S) - (S&common) # add set, remove duplicates
common |= S # track seen items
print(unique)
{5, 6, 7, 8, 9}