假设我有这些数字集
a = {1, 2, 3}
b = {2, 3, 4}
c = {1, 5}
我想找到集合的所有不同数字分组。结果将是
{1}, {2, 3}, {4}, {5}
我天真的方法,不起作用,是这样的:
data = [{1, 2, 3}, {2, 3, 4}, {1, 5}]
for i in range(1, 5):
s = set.intersection(*[x for x in data if i in x])
print(s)
返回
set([1])
set([2, 3])
set([2, 3])
set([2, 3, 4])
哪些可以轻易去重复,但不会给出预期的结果。
如何才能获得集合子集中存在的数字分组?
答案 0 :(得分:5)
您的代码有两个问题:
5
,但range
不包含停靠点,因此您不会检查5。因此,通过修复这些问题,代码将如下所示:
data = [{1, 2, 3}, {2, 3, 4}, {1, 5}]
for i in range(1, 6):
useful_sets = [x for x in data if i in x]
if len(useful_sets) <= 1:
print(set([i]))
else:
s = set.intersection(*useful_sets)
print(s)
# prints:
# {1}
# {2, 3}
# {2, 3}
# {4}
# {5}
要获得完整(而非重复)的结果,您可以将它们存储为一组中的frozensets:
data = [{1, 2, 3}, {2, 3, 4}, {1, 5}]
res = set()
for i in range(1, 6):
useful_sets = [x for x in data if i in x]
if len(useful_sets) <= 1:
res.add(frozenset([i]))
else:
s = set.intersection(*useful_sets)
res.add(frozenset(s))
print(res)
# {frozenset({5}), frozenset({4}), frozenset({2, 3}), frozenset({1})}
哪个(订购除外)应该是你想要的。