简体   繁体   English

Python-替代list.remove(x)?

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

I wish to compare two lists. 我想比较两个清单。 Generally this is not a problem as I usually use a nested for loop and append the intersection to a new list. 通常这不是问题,因为我通常使用嵌套的for循环并将交集附加到新列表中。 In this case, I need to delete the intersection of A and B from A. 在这种情况下,我需要从A中删除A和B的交集。

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

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

My objective is to compare A and B and delete A intersection B from A, ie, delete A[0][0] in this case. 我的目标是比较A和B并从A删除A交集B,即在这种情况下删除A [0] [0]。

I tried: 我试过了:

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) throws a ValueError. list.remove(x)引发ValueError。

If possible (meaning if the order and the fact that you have "sublists" does not matter), I would first flatten the lists , create sets and then you can easily remove the elements from A that are in B : 如果可能(意味着顺序和您拥有“子列表”的事实无关紧要),我首先将列表展平 ,创建集合 ,然后可以轻松地从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'])

Or if the order and structure of A matters, you can do (thanks and credits to THC4k ): 或者,如果A的顺序和结构A重要,则可以这样做(感谢并感谢THC4k ):

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

But note: This only works under the assumption that A and B will be always lists of lists. 但是请注意:这仅在AB 始终为列表列表的前提下起作用。

A naive approach using sets and itertools. 使用集合和迭代工具的幼稚方法。 You can tweak this further according to your requirements: 您可以根据自己的要求进一步进行调整:

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

Edit: To use remove in a situation like this, you can't directly remove j ('ab') in this case from the list a, since it is a nested list. 编辑:在这种情况下要使用删除,在这种情况下,您不能直接从列表a中删除j('ab'),因为它是一个嵌套列表。 You would have to use A.remove(['ab']) or A.remove([j]) to accomplish this. 您必须使用A.remove(['ab'])或​​A.remove([j])来完成此操作。

Another possibility is the pop(int) method. 另一种可能性是pop(int)方法。 So A.pop(index) should actually work as well. 因此A.pop(index)实际上也应该工作。

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

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

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