Skip to main content
 首页 » 编程设计

Python:如何获取仅出现在集合列表中的一组中的项目

2025年05月04日43mfrbuaa

我想创建一个函数,它接受一个或多个集合的列表,并找到列表中所有集合的对称差异,即结果应该是一组值,每个值只包含在一个的个人集。 (如果我对这是对称差异有误,请纠正我。)

例如:

>>> s1 = set([1, 2, 3]) 
>>> s2 = set([2, 3, 4]) 
>>> s3 = set([2, 3, 7]) 
>>> s4 = set([2, 5, 9]) 
>>> myfunc([s1, s2, s3, s4]) 
{1, 4, 5, 7, 9} 

是否有内置的东西可以用来代替 myfunc?或者我使用这样的东西:

def myfunc(sets: List[set]) -> set: 
 
    sd = set() 
    goners = set() 
    for s in sets: 
        still_ok = s - goners 
        sd = sd.symmetric_difference(still_ok) 
        goners = goners.union(s.difference(sd)) 
    return sd 

是否有更好/更高效/“Pythonic”的方式来做到这一点?

请您参考如下方法:

对于可以同时使用运算符和函数完成的内置 Python 对象的操作,运算符版本通常比函数版本更快,因为在访问实例属性和进行显式函数调用方面存在开销。此外,对集合执行就地更新可以避免创建额外的数据副本并提高程序效率。

使用集合运算符的方法的改进版本如下所示:

def myfunc_improved(sets: List[set]) -> set: 
    sd = set() 
    goners = set() 
    for s in sets: 
        sd ^= s - goners 
        goners |= s - sd 
    return sd 

性能测量:

%timeit myfunc(sets) 
%timeit myfunc_improved(sets) 
 
3.19 µs ± 34.3 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) 
1.75 µs ± 11.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)