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

标签 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')]

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

最佳答案

问题是 l1 是元组列表的列表(即 [[tuple]]),而 l2 是元组列表(即 [tuple] ).如果你改变这个,列表理解的输出就是你所期望的:

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')]

关于python - 检查元组列表是否是另一个元组的子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38676711/

相关文章:

python - PyQT 使用循环向选项卡添加数据/信息

python - Docker:通过共享PID namespace 从UID获取主机用户名

python - 使用一维 bool 数组进行 Numpy 索引

c++ - 如何实现 set::find() 以仅匹配一对中的键?

java - 从 Set Java 8 中删除一个元素

Mysql SET 引用外键

python - 在Python中检查文件是否被修改

python - 在 Python 中一次更改列表中的多个项目

python - 如何使用列表中的数据创建带有新 KEY 的字典?

list - 在 Scala 中从另一个列表的成员创建列表的最佳方法