>>> x1=[["x1","y1"],["x1","x2"]]
>>> x2=[["x1","y1"],["x1","x2"],["x2","y2"]]
>>> x2-x1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'list' and 'list'
>>> set(x2)-set(x1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
我想区分两个列表,我想要的结果是["x2","y2"]
。我怎么能得到它?
答案 0 :(得分:3)
您可以通过检查元素来执行以下操作:
x1=[["x1","y1"],["x1","x2"]]
x2=[["x1","y1"],["x1","x2"],["x2","y2"]]
>>> print [i for i in x2 if i not in x1]
[['x2', 'y2']]
答案 1 :(得分:2)
另一个解决方案在O(N ^ 2)中运行,此解决方案以O(N + M)时间复杂度运行。
x1 = [["x1", "y1"], ["x1", "x2"]]
x2 = [["x1", "y1"], ["x1", "x2"], ["x2", "y2"]]
set1 = {tuple(item) for item in x1}
print [item for item in x2 if tuple(item) not in set1]
# [['x2', 'y2']]
只需将第一组项目转换为元组列表,然后使用元组创建一个集合。然后,对于下一个列表列表中的每个项目,将其转换为元组并检查它是否在集合中。