使用集合(列表)理解的对称集合差分不能给出预期结果

2024-03-29 09:08:10 发布

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

我正在学习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)应该是可行的。我想知道为什么没有


Tags: and代码in元素列表forifnot
2条回答

因为你把生成器转换成了一个列表!你知道吗

所以它相当于一个列表!!!你知道吗

另一种选择是:

list(set(l)^set(m))

很短很好。你知道吗

list(set(l) - set(m)) + list(set(m) - set(l))是寻找两个集合之间的symmetric difference的一种迂回的方法(“在两个集合中的任何一个集合中而不是在它们的交集中的元素集合”-Wikipedia)。你知道吗

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

…我不推荐。你知道吗

相关问题 更多 >