我正在学习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的一种有风的方法(“元素集合位于两个集合中的任何一个,但不在它们的交集中” — 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}
...不是我会推荐的。