Python - list.remove(x)的替代品?

Dar*_*ick 1 python comparison list

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

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

 B = [['ab'], ['hi'], ['op'], ['ej']]
Run Code Online (Sandbox Code Playgroud)

我的目标是比较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)
Run Code Online (Sandbox Code Playgroud)

list.remove(x)抛出一个ValueError.

Fel*_*ing 9

如果可能的话(这意味着如果为了和你有"子列表"没关系的事实),我首先压平列表,创建,然后你可以轻松地删除从要素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'])
Run Code Online (Sandbox Code Playgroud)

或者如果A事情的顺序和结构,你可以做(​​感谢和信任 THC4k):

>>> remove = set(chain(*B))
>>> A = [[x for x in S if x not in remove] for S in A].
Run Code Online (Sandbox Code Playgroud)

但要注意:假设下才会有效A,并B一直列表的列表.

  • 不,你的很棒,我只是"希望"列表清单有充分的理由;-) (2认同)