我有一个包含数千个与此类似的集合的列表:
set_list = [a, b, c, d]
列表中的每个设置如下所示:
a = set([1, 2, 3, 4, 5])
b = set([4, 5, 6, 7, 7, 9])
c = set([1, 2, 6, 8, 10, 12, 45])
d = set([11, 3, 23, 3, 4, 44])
我想进行设置操作:例如,列表中的每个设置都使用X-(YUZUAUB ......等),如下所示:
在set_list
中的所有元素上应用此操作后,新元素将如下所示:
a = a.difference(b.union(c, d))
b = b.difference(c.union(a, d))
c = c.difference(d.union(b, a))
d = d.difference(a.union(c, b))
我如何做到这一点?
答案 0 :(得分:3)
一种可能性是利用multiset
module来预先计算fetchData(){
return this.http.get('assets/ninjas.json');
}
中所有元素的多集并集,就像这样:
set_list
在这里,{{ 1}}用您的符号计算from multiset import Multiset
union = sum(set_list, Multiset())
set_list = [s - (union - s) for s in set_list]
。
有关仅使用标准库实现的方法(更详细地说,请参见Aran-Fey's answer)。
答案 1 :(得分:1)
如果我理解正确,那么您希望每个集合都具有差异,而其余集合则需要并集。我将使用循环以及functools.reduce
和operator.or_
:
设置
import functools
import operator
a = set([1, 2, 3, 4, 5])
b = set([4, 5, 6, 7, 7, 9])
c = set([1, 2, 6, 8, 10, 12, 45])
d = set([11, 3, 23, 3, 4, 44])
set_list = [a, b, c, d]
循环并保存结果
# I don't know what you want to do with the results so
# I'll save them in a list...
results = []
for i in set_list:
list_copy = list(set_list)
list_copy.remove(i)
r = i - functools.reduce(operator.or_, list_copy)
results.append(r)
print(results)
# prints [set(), {9, 7}, {8, 10, 12, 45}, {11, 44, 23}]
答案 2 :(得分:1)
[value - {item for subset in set_list[0:index] + set_list[index + 1:] for item in subset} for index, value in enumerate(set_list)]
这意味着:
result = []
for index, value in enumerate(set_list):
union = {
item
for subset in set_list[0:index] + set_list[index + 1:]
for item in subset
}
result.append(value - union)
print(result)
输出:
[set(), {9, 7}, {8, 10, 12, 45}, {11, 44, 23}]
答案 3 :(得分:1)
这是使用标准库中的NPE's answer对collections.Counter
的重新实现:
from collections import Counter
def mutual_difference(set_list):
# create a multiset out of the union of all sets
union = Counter()
for s in set_list:
union.update(s)
new_set_list = []
for s in set_list:
# subtract s from the union and discard 0-count elements
union.subtract(s)
union += {}
# take the difference
new_set_list.append(s.difference(union))
# add s to the union again
union.update(s)
return new_set_list
示例:
>>> mutual_difference([{1,2}, {2,3}, {1,4,5}])
[set(), {3}, {4, 5}]