[英]How to create a new set of all elements that are in only one of multiple sets?
I need the code to:我需要代码:
Example:例子:
A{1,2,3,4,5} A{1,2,3,4,5}
B{1,2,3,4,6}乙{1,2,3,4,6}
C{1,3,4,7} C{1,3,4,7}
D{1,8,9} D{1,8,9}
Set E would look like: {5,6,7,8,9}集合 E 看起来像:{5,6,7,8,9}
For context: a different part of the question was to make a set with elements of numbers that were divisible by 3,5,7 and 11. This is code from that part of the question, and now I'm looking to do this new part.对于上下文:问题的一个不同部分是用可被 3、5、7 和 11 整除的数字元素创建一个集合。这是问题那部分的代码,现在我正在做这个新的部分。 I'm sure there's a better way to do this however I'm only 2 months in of self-teaching and I would like to just know what to do for this question.
我确信有更好的方法可以做到这一点,但是我只有 2 个月的自学时间,我只想知道如何解决这个问题。
set3_list=[]
for x in range(1,501):
if(x%3==0):
set3_list.append(x)
set5_list=[]
for y in range(1,501):
if(y%5==0):
set5_list.append(y)
set7_list=[]
for z in range(1,501):
if(z%7==0):
set7_list.append(z)
set21_list=[]
for a in range(1,501):
if(a%11==0):
set21_list.append(a)
s3=set(set3_list)
s5=set(set5_list)
s7=set(set7_list)
s21=set(set21_list)
How about pooling all the sets (allowing for duplicates), counting the elements, and then take elements that occur only once?如何汇集所有集合(允许重复),计算元素,然后获取仅出现一次的元素?
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}
If you are somewhat reluctant to import modules, the following is equivalent:如果你有点不愿意导入模块,下面是等价的:
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}
One way to do this is to unpack all the sets into a list.一种方法是将所有集合解包到一个列表中。 Then iterate over a union of them all getting their counts:
然后迭代它们的联合以获取它们的计数:
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}
This can be made more efficient if you use collections.Counter
for joined
and itertools.chain
:这可以更加有效的,如果你使用
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}
You could loop on sets and accumulate a unique and common set to extract the desired result:您可以在集合上循环并累积一个独特且通用的集合以提取所需的结果:
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}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.