How can I get the difference between two lists?
本问题已经有最佳答案,请猛点这里访问。
1 2 3 4 5 6 7 8 9 10 | >>> 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' |
我想知道两个列表之间的区别,这里我想要的结果是
您可以通过检查元素来执行以下操作:
1 2 3 4 5 6 | 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']] |
另一个解决方案运行在O(n^2)中,当此解决方案运行在O(n+m)时间复杂性中时。
1 2 3 4 5 | 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']] |
只需将第一组项转换为元组列表,然后用元组创建一个集合。然后,对于下一个列表中的每个项,将其转换为元组,并检查它是否在集合中。