簡體   English   中英

使用深層復制從 Python 中的列表列表中刪除重復項

[英]Removing duplicates from a list of lists in Python using deep copy

我有一個字典列表 - list_1 = [{'account': '1234', 'email': 'abc@xyz.com'}, ... , ...] 我想刪除包含重復電子郵件的條目名單。

import copy
list_2 = copy.deepcopy(list_1)
for i in mainList
 for j in range(len(list_2)-1, -1, -1):
   if ((list_2[j]["email"] == mainList[i])):
                    list_1.remove(list1[j])

這里的 MainList 是我用來比較值的電子郵件列表。 mainList 看起來像: ['abc@xyz.com', 'efg@cvb.com, ..., ...] 主要問題是 list_1 沒有正確輸出。 如果我使用列表、切片甚至列表理解來復制它,它就會變成空的。 最終結果應該給出 list_1,其中每個 email 只包含一個元素/列表/字典。 使用復制或深復制至少給了我一些東西。 有時我似乎也會遇到索引錯誤。 使用

for x in list_2:

相反,返回 list_1 只有一項。 我最接近正確答案的是在刪除項目時迭代 list_1 本身,但它不是 100% 正確的。 請幫忙。

遍歷您的字典列表並僅在新字典中不存在時才將每個 email 保存。

temp = dict()
list_1 = [{'account': '1234', 'email': 'abc@xyz.com'}]
for d in list_1:
    if d['email'] in temp:
        continue
    else:
        temp[d['email']] = d
final_list = list(temp.values())

好像你想刪除重復的字典。 請在問題中提及重復的字典。

di = [{'account': '1234', 'email' : 'abc@xyz.com'}, {'account1': '12345', 
'email1' : 'abcd@xyz.com'}, {'account': '1234', 'email' : 'abc@xyz.com'}]
s=[i for n, i in enumerate(d) if i not in di[n + 1:]]
Print(s)

這將為您提供所需的 output

[{'account1': '12345', 'email1': 'abcd@xyz.com'}, {'account': '1234', 'email': 
'abc@xyz.com'}]

我覺得完成此操作的最簡單方法是根據您的鍵創建list_1的索引版本(字典)。

list_1 = [
    {'account': '1234', 'email' : 'abc@xyz.com'},
    {'account': '1234', 'email' : 'abc@xyz.com'},
    {'account': '4321', 'email' : 'zzz@xyz.com'},
]

list_1_indexed = {}
for row in list_1:
    list_1_indexed.setdefault(row['email'], row)
list_2 = list(list_1_indexed.values())

print(list_2)

這會給你:

[
    {'account': '1234', 'email': 'abc@xyz.com'},
    {'account': '4321', 'email': 'zzz@xyz.com'}
]

我不確定我會推薦它,但如果你想使用理解,你可以這樣做:

list_2 = list({row['email']: row for row in list_1}.values())

請注意,第一個策略導致第一個鍵行獲勝,而理解最后一個鍵行獲勝。

暫無
暫無

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

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