【问题标题】:How can I get the difference between two lists? [duplicate]我怎样才能得到两个列表之间的区别? [复制]
【发布时间】:2014-08-27 01:59:18
【问题描述】:
>>> 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"]。我怎样才能得到它?

【问题讨论】:

    标签: python


    【解决方案1】:

    你可以通过检查元素来做到这一点:

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

    【讨论】:

    • @lejlot,谢谢。我把它放在一个单独的行上,因为我相信每次都会创建这个系列或其他东西。
    • 无法对列表进行哈希处理...
    • @thefourtheye,抱歉,我的错。
    • 最坏情况复杂度是 O(N ^ 2),而我的解决方案是 O(N + M)
    【解决方案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']]
    

    只需将第一组项目转换为元组列表,然后使用元组创建一个集合。然后,对于下一个列表中的每个项目,将其转换为元组并检查它是否不在集合中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-12
      • 2019-06-21
      • 1970-01-01
      • 2012-03-28
      • 2021-07-05
      • 1970-01-01
      • 2020-06-07
      相关资源
      最近更新 更多