簡體   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