如何获取两个列表之间的差异?

-3 投票
2 回答
771 浏览
提问于 2025-04-18 12:16
>>> 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"]。我该怎么做呢?

2 个回答

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

首先把第一组项目转换成一个元组的列表,然后用这些元组创建一个集合。接着,对于下一个列表中的每个项目,把它转换成元组,检查这个元组是否不在集合里。

撰写回答