簡體   English   中英

從Python中的列表列表中刪除重復項

[英]Removing duplicates from list of lists in Python

如果想要根據每個嵌套列表的第一個元素評估重復項,是否有人可以建議一個很好的解決方案來從嵌套列表中刪除重復項?

主要列表如下所示:

L = [['14', '65', 76], ['2', '5', 6], ['7', '12', 33], ['14', '22', 46]]

如果在第一個位置[k][0]上有另一個具有相同元素的列表已經發生,那么我想刪除該列表並獲得此結果:

L = [['14', '65', 76], ['2', '5', 6], ['7', '12', 33]]

你能建議一種算法來實現這個目標嗎?

您是否關心保留訂單/刪除哪些副本? 如果沒有,那么:

dict((x[0], x) for x in L).values()

會做的。 如果您想保留訂單,並希望保留您找到的第一個訂單:

def unique_items(L):
    found = set()
    for item in L:
        if item[0] not in found:
            yield item
            found.add(item[0])

print list(unique_items(L))

改為使用dict,如下所示:

L = {'14': ['65', 76], '2': ['5', 6], '7': ['12', 33]}
L['14'] = ['22', 46]

如果您從某些外部源接收第一個列表,請將其轉換為:

L = [['14', '65', 76], ['2', '5', 6], ['7', '12', 33], ['14', '22', 46]]
L_dict = dict((x[0], x[1:]) for x in L)

我不確定你的“另一個名單”是什么意思,所以我假設你在L里面說那些名單

a=[]
L = [['14', '65', 76], ['2', '5', 6], ['7', '12', 33], ['14', '22', 46],['7','a','b']]
for item in L:
    if not item[0] in a:
        a.append(item[0])
        print item

如果訂單無關緊要,請在下方編寫代碼

print [ [k] + v for (k, v) in dict( [ [a[0], a[1:]] for a in reversed(L) ] ).items() ]

[['2','5','6'],['14','65','76'],['7','12','33']]

使用熊貓:

import pandas as pd

L = [['14', '65', 76], ['2', '5', 6], ['7', '12', 33], ['14', '22', 46],['7','a','b']]

df = pd.DataFrame(L)
df = df.drop_duplicates()

L_no_duplicates = df.values.tolist()

如果要刪除特定列中的重復項,請僅使用:

df = df.drop_duplicates([1,2])

暫無
暫無

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

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