簡體   English   中英

從列表中刪除常見元素

[英]Removing common elements from lists

使用這些列表:

a=[2,6,79,10]
b=[6,7,2,0,8,5]

所需的輸出將是:

a=[79,10]
b=[7,0,8,5]

為什么此代碼不起作用?

def cel(a,b):
    for x in a:
        if x in b:
            b.remove(x)
            a.remove(x)

您可以為此使用set操作:

i = set(a).intersection(set(b))
a = list(set(a).difference(i))
b = list(set(b).difference(i))

編輯我嘗試調試您的原始代碼,並意識到,只要刪除一個數字,它就會跳過一個數字。 谷歌搜索后,我發現由於一些內部索引問題, 在迭代時修改列表不是定義的行為 最簡單的解決方法是在for循環中使用原始數組的副本為:

for x in a[:]:
    if x in b:
        b.remove(x)
        a.remove(x)

@gokcehan答案中保留順序的算法是三次O(n**3) 即使對於中等大小的列表,它也是非常低效的(Programming Pearls書中有一個示例,其中Basic中的線性算法優於C中的立方算法(分鍾vs.天))。

您可以保留訂單並在線性時間內運行它:

common = set(a).intersection(b)
a = [x for x in a if x not in common]
b = [x for x in b if x not in common]

您可以就地進行:

def remove_items(lst, items):
    items = set(items) # unnecessary in your case
    pos = 0
    for x in lst:
        if x not in items:
           lst[pos] = x # save
           pos += 1
    del lst[pos:]

common = set(a).intersection(b)
remove_items(a, common)
remove_items(b, common)

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM