繁体   English   中英

Python-替代list.remove(x)?

[英]Python - alternative to list.remove(x)?

我想比较两个清单。 通常这不是问题,因为我通常使用嵌套的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。

如果可能(意味着顺序和您拥有“子列表”的事实无关紧要),我首先将列表展平 ,创建集合 ,然后可以轻松地从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的顺序和结构A重要,则可以这样做(感谢并感谢THC4k ):

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

但是请注意:这仅在AB 始终为列表列表的前提下起作用。

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

#!/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']]

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM