簡體   English   中英

在字典列表中查找部分重復項

[英]Find partly duplicates in a list of dictionaries

我有一個這樣的列表:

my_list =
    [
    {'name': 'avg', 'indexes': [3]}, 
    {'name': 'sma', 'indexes': [2, 3]}
    ]

我想有效地找到indexes鍵有 1 個項目的所有字典,它存在於另一個有 2 個字典中,並將其刪除。 (這里[3][2,3]中)

基本上找到重復項並刪除較短的列表。

例如,在這種情況下,刪除: {'name': 'avg', 'indexes': [3]} ,我們通常可能有多個。

indexes數組的長度可以是1>1 ,我們要檢查len(dic)=1是否在len(dic) > 1 的 dic 中

首先從具有多個索引的列表中收集所有索引,然后使用它來過濾:

my_list = [
    {'name': 'avg', 'indexes': [3]}, 
    {'name': 'sma', 'indexes': [2, 3]}
]

remove = {x
          for d in my_list
          if len(d['indexes']) > 1
          for x in d['indexes']}

my_list = [d
           for d in my_list
           if len(d['indexes']) != 1
           or d['indexes'][0] not in remove]

print(my_list)

暫無
暫無

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

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