在元素列表上设置操作

2024-04-27 00:25:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个清单,里面有几千套类似的东西:

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])

我想对列表中的每一个集合执行set操作:X-(YUZUAUB……etc),例如,这看起来像这样: 对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))

我如何做到这一点?你知道吗


Tags: 元素内容列表etclistunionset新元素
3条回答

这是使用标准库中的^{}重新实现NPE's answer

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}]

一种可能性是利用^{} module预计算set_list中所有元素的多集并,如下所示:

from multiset import Multiset
union = sum(set_list, Multiset())
set_list = [s - (union - s) for s in set_list]

这里,union - s计算符号中的Y ∪ Z ∪ A ∪ B...。你知道吗

请参见Aran-Fey's answer,了解仅使用标准库实现的相同方法(更详细)。你知道吗

如果我理解正确的话,你需要每个集合的差和其他集合的并集。我会使用循环和functools.reduceoperator.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}]

相关问题 更多 >