Skip to main content
 首页 » 编程设计

python之使用集合(列表)理解的对称集合差异未给出预期结果

2024年08月14日41tintown

我正在学习 python,想了解这里发生的事情。我确定我缺少一些基本的东西。我从两个列表中获取的元素都没有出现在两个列表中。这是我的输出代码:

    l = [1, 8, 3, 4] 
    m = [4, 6, 3, 8] 
 
    Method 1: 
    r = list(set(l) - set(m)) + list(set(m) - set(l)) 
    [1, 6] 
 
    Method 2: 
    print [(x,y) for x in l for y in m if x not in m and y not in l] 
    [(1, 6)] 
 
    Method 3 (same but returns a list): 
    print [[x,y] for x in l for y in m if x not in m and y not in l] 
    [[1, 6]] 

我想要一个列表理解,它会返回与方法 1 返回的列表相同的列表。

此外,据我所知,由于列表理解中的代码,我得到了一个生成器。但是,我无法将它变成一个简单的列表:

    res = ((x,y) for x in l for y in m if x not in m and y not in l) 
    print list(res) 
    [(1, 6)] 

这是为什么呢?我期待:

    [1, 6] 

编辑:我的主要问题是:为什么我不能将生成器从上面的列表推导式转换为列表?根据 this question 中接受的答案使用 list(res) 应该可以。我想了解为什么没有。

请您参考如下方法:

list(set(l) - set(m)) + list(set(m) - set(l)) 是一种寻找 symmetric difference 的简单方法两个集合之间(“元素集合在其中一个集合中但不在它们的交集中”——维基百科)。

>>> set(l).symmetric_difference(m) 
{1, 6} 

无论如何,有了列表理解,我会这样做:

>>> {el for (this,other) in [(m,l),(l,m)] for el in this if el not in other} 
{1, 6} 

与

相同
>>> symdif = set() 
>>> for this,other in [(m,l),(l,m)]: 
...     for el in this: 
...          if el not in other: 
...              symdif.add(el) 
... 
>>> symdif 
{1, 6} 

...并不是说我会推荐它。