检查元组列表是否是另一个元组的子集

时间:2016-07-30 17:37:30

标签: python list set

首先,请注意我已经完成了其他列表子集问题,并且它们与我的问题无关。

我有两个列表

>>> l1 = [[(7, -1, 'VBD', 'null', -1, 'looked', 'looked'), (8, 7, 'JJ', 'xcomp', -1, 'shocked', 'shocked')]]
>>>
>>> l2 = [(7, -1, 'VBD', 'null', -1, 'looked', 'looked'), (8, 7, 'JJ', 'xcomp', -1, 'shocked', 'shocked'), (9, 8, 'CC', 'cc', -1, 'and', 'and'), (10, 7, 'JJ', 'xcomp', -1, 'angry', 'angry')]

我正在尝试检查一个是否是另一个的子集。

但在此之前我检查了从另一个列表中减去一个列表的结果,我得到了令人失望的结果 -

>>> [word for word in l1 if word not in l2]
[[(7, -1, 'VBD', 'null', -1, 'looked', 'looked'), (8, 7, 'JJ', 'xcomp', -1, 'shocked', 'shocked')]]

>>> [word for word in l2 if word not in l1]
[(7, -1, 'VBD', 'null', -1, 'looked', 'looked'), (8, 7, 'JJ', 'xcomp', -1, 'shocked', 'shocked'), (9, 8, 'CC', 'cc', -1, 'and', 'and'), (10, 7, 'JJ', 'xcomp', -1, 'angry', 'angry')]

为什么我的结果会得到相同的列表? 这是否与它们是元组的事实有关?

3 个答案:

答案 0 :(得分:5)

问题是l1是元组列表的列表(即[[tuple]]),而l2是元组列表(即[元组])。如果更改此列表,那么列表推导的输出就是您所期望的:

l1 = [(7, -1, 'VBD', 'null', -1, 'looked', 'looked'), (8, 7, 'JJ', 'xcomp', -1, 'shocked', 'shocked')]
l2 = [(7, -1, 'VBD', 'null', -1, 'looked', 'looked'), (8, 7, 'JJ', 'xcomp', -1, 'shocked', 'shocked'), (9, 8, 'CC', 'cc', -1, 'and', 'and'), (10, 7, 'JJ', 'xcomp', -1, 'angry', 'angry')]
​
a = [word for word in l1 if word not in l2]
b = [word for word in l2 if word not in l1]
​
print a
print b

[]
[(9, 8, 'CC', 'cc', -1, 'and', 'and'), (10, 7, 'JJ', 'xcomp', -1, 'angry', 'angry')]

答案 1 :(得分:2)

使用issubset

l1 = [(7, -1, 'VBD', 'null', -1, 'looked', 'looked'), (8, 7, 'JJ', 'xcomp', -1, 'shocked', 'shocked')]
l2 = [(7, -1, 'VBD', 'null', -1, 'looked', 'looked'), (8, 7, 'JJ', 'xcomp', -1, 'shocked', 'shocked'), (9, 8, 'CC', 'cc', -1, 'and', 'and'), (10, 7, 'JJ', 'xcomp', -1, 'angry', 'angry')]

>>> set(l1).issubset(l2)
True

答案 2 :(得分:0)

您可以使用集合和< =运算符(是子集)。

<header>
  <h1>
    Hello
  </h1>
</header>
<section>
  test
</section>