簡體   English   中英

從Python的列表中刪除兩個重復的元素

[英]Delete both repeated elements from a list of lists in Python

我有清單

輸入:
L = [[1, 2, 3], [2, 3, 4], [5, 6, 7], [2, 3, 4], [2, 3, 5], [1, 2, 3], [1, 2, 3]]

輸出:
L= [[5, 6, 7], [ 2, 3, 5]]

我想檢查L[i]== L[j] ,然后將L[j]從列表中刪除。

你能幫助我嗎?

這是我的代碼:

for i in range(0,len(L) - 1):
    for j in range(1,len(L) - 1):
        if (L[i] == L[j]):
            L.remove(L[j])

print(L)

但是它給出了一個錯誤:

if (L[i] == L[j]):
IndexError: list index out of range

一旦你刪除的元素L ,形狀L變化。 這就是為什么出現索引超出范圍錯誤的原因:您仍然在L的原始長度上進行迭代,但是一旦從L刪除元素,它的長度就會變得更短。

您可以通過創建一個帶有count的新列表來解決此問題:

L2 = [sublist for sublist in L if L.count(sublist) == 1]

print(L2)
>>> [[5, 6, 7], [2, 3, 5]]

注意:您的當前邏輯即使適應了L的變化長度,也不會返回您想要的輸出。 它仍將保留所有重復元素的第一個“副本”,如下面的Richard Rublev的回答所產生的。


如果這太慢(O(n 2 )),這是使用Counter的O(n)解決方案:

from collections import Counter

# Converting elements to hashable type
L = [tuple(sublist) for sublist in L]
cnt = Counter(L)

# Grabbing non-duplicated items
L2 = [k for k, v in cnt.items() if v == 1]

# Converting elements back to lists
L2 = [list(sublist) for sublist in L2]

print(L2)   
>>> [[5, 6, 7], [2, 3, 5]]

嘗試這個

testdata = [[1, 2, 3], [2, 3, 4], [5, 6, 7], [2, 3, 4], [2, 3, 5], [1, 2, 3], [1, 2, 3]]
unique = [list(x) for x in set(tuple(x) for x in testdata)]

結果

[[2, 3, 5], [2, 3, 4], [5, 6, 7], [1, 2, 3]]

暫無
暫無

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

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