【问题标题】:Python - alternative to list.remove(x)?Python - list.remove(x) 的替代品?
【发布时间】:2010-06-02 13:20:27
【问题描述】:

我想比较两个列表。通常这不是问题,因为我通常使用嵌套的 for 循环并将交集附加到新列表中。在这种情况下,我需要从 A 中删除 A 和 B 的交集。

 A = [['ab', 'cd', 'ef', '0', '567'], ['ghy5'], ['pop', 'eye']]

 B = [['ab'], ['hi'], ['op'], ['ej']]

我的目标是比较A和B并从A中删除A交集B,即在这种情况下删除A[0][0]。

我试过了:

def match():
    for i in A:
        for j in i:
            for k in B:
                for v in k:
                    if j == v:
                        A.remove(j)

list.remove(x) 抛出 ValueError。

【问题讨论】:

    标签: python comparison list


    【解决方案1】:

    如果可能(意味着如果顺序和您拥有“子列表”的事实无关紧要),我会首先flatten the lists,创建sets,然后您可以轻松地从A 中删除位于B:

    >>> from itertools import chain
    >>> A = [['ab', 'cd', 'ef', '0', '567'], ['ghy5'], ['pop', 'eye']]
    >>> B = [['ab'], ['hi'], ['op'], ['ej']]
    >>> A = set(chain(*A))
    >>> B = set(chain(*B))
    >>> A-B
    set(['ghy5', 'eye', 'ef', 'pop', 'cd', '0', '567'])
    

    或者如果A 的顺序和结构很重要,您可以这样做(感谢THC4k):

    >>> remove = set(chain(*B))
    >>> A = [[x for x in S if x not in remove] for S in A].
    

    但请注意:这仅在 AB 将是始终列表列表的假设下有效。

    【讨论】:

    • @THC4k:如果您想提供您的评论作为答案,我会将我的答案改回原来的答案。
    • 不,你的很棒,我只是“希望”这个列表有充分的理由 ;-)
    【解决方案2】:

    使用集合和迭代工具的简单方法。您可以根据自己的要求进一步调整:

    #!/usr/bin/env python
    
    a = [['ab', 'cd', 'ef', '0', '567'], ['ghy5'], ['pop', 'eye']]
    b = [['ab'], ['hi'], ['op'], ['ej']]
    
    from itertools import chain
    
    # this results in the intersection, here => 'ab'
    intersection = set(chain.from_iterable(a)).intersection(
        set(chain.from_iterable(b)))
    
    def nested_loop(iterable):
        """
        Loop over arbitrary nested lists.
        """
        for e in iterable:
            if isinstance(e, list):
                nested_loop(e)
            else:
                if e in intersection:
                    iterable.remove(e)
        return iterable
    
    print nested_loop(a)
    # => 
    # [['cd', 'ef', '0', '567'], ['ghy5'], ['pop', 'eye']]
    

    【讨论】:

      【解决方案3】:

      编辑:要在这种情况下使用 remove,在这种情况下,您不能直接从列表 a 中删除 j ('ab'),因为它是一个嵌套列表。您必须使用 A.remove(['ab']) 或 A.remove([j]) 来完成此操作。

      另一种可能性是 pop(int) 方法。所以 A.pop(index) 实际上应该也可以工作。

      来源:http://docs.python.org/tutorial/datastructures.html

      【讨论】:

      • ? j 始终是 A 中列表的一个元素。它不是索引。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-27
      • 2021-02-11
      • 2014-05-17
      相关资源
      最近更新 更多