簡體   English   中英

如何刪除 python 中第二個列表中的列表中的項目?

[英]How to remove the items in a list that are in a second list in python?

我有一個列表列表和另一個列表,我想從第二個列表中的列表列表中刪除所有項目。

first = [[1,3,2,4],[1,2],[3,4,2,5,1]]
to_remove = [1,2]

一般來說,我會如何處理這個問題?

這里也有類似的問題,但沒有任何幫助。


result = []
for l in first:
    tmp = []
    for e in l:
        if e not in to_remove:
            tmp.append(e)
    result.append(tmp)

print(result)

如果元素在 to_remove 列表中,則此代碼循環遍歷所有列表和每個列表的所有元素,它將跳過它,並將 go 轉到下一個。 所以如果你有多個實例,它將刪除它

最良好的問候

使用sets的優雅解決方案:

first = [[1,3,2,4],[1,2],[3,4,2,5,1]]
to_remove = [1,2]
result = [list(set(x).difference(to_remove)) for x in first]
result
[[3, 4], [], [3, 4, 5]]

暫無
暫無

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

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