从dicts Python列表中删除值接近重复的dict

2024-09-26 17:52:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我想根据以下规则清理dict列表:

1)dict列表已经排序,因此优先选择较早的dict。
2) 在较低的dict中,如果['name']['code']字符串值与列表中更高的任何dict的相同键值匹配,并且如果这两个dict之间的int(['cost'])的差值的绝对值是< 2;那么该dict被认为是前面dict的副本,并从列表中删除。在

以下是dict列表中的一个dict:

{
'name':"ItemName", 
'code':"AAHFGW4S",
'from':"NDLS",
'to':"BCT",
'cost':str(29.95)
 }

像这样删除重复项的最佳方法是什么?在


Tags: 字符串namefrom列表排序规则副本code
3条回答

可能还有一种更像Python的方法来实现这一点,但这是基本的伪代码:

def is_duplicate(a,b):
  if a['name'] == b['name'] and a['cost'] == b['cost'] and abs(int(a['cost']-b['cost'])) < 2:
    return True
  return False

newlist = []
for a in oldlist:
  isdupe = False
  for b in newlist:
    if is_duplicate(a,b):
      isdupe = True
      break
  if not isdupe:
    newlist.append(a)

这是一个复杂的问题,但我认为这样的方法会奏效:

for i, d in enumerate(dictList):
    # iterate through the list of dicts, starting with the first
    for k,v in d.iteritems():
        # for each key-value pair in this dict...
        for d2 in dictList[i:]:
             # check against all of the other dicts "beneath" it
             # eg,
             # if d['name'] == d2['name'] and d['code'] == d2['code']:
             #      check the cost stuff here 

既然你说成本是整数,那么你可以使用:

def neardup( items ):
    forbidden = set()
    for elem in items:
        key = elem['name'], elem['code'], int(elem['cost'])
        if key not in forbidden:
            yield elem
            for diff in (-1,0,1): # add all keys invalidated by this
                key = elem['name'], elem['code'], int(elem['cost'])-diff
                forbidden.add(key)

下面是一种不那么复杂的方法来计算差异:

^{pr2}$

这两种解决方案都避免重新扫描每个项目的整个列表。毕竟,只有在(name, code)相等的情况下,成本才会变得有趣,所以您可以使用字典快速查找所有候选项。在

相关问题 更多 >

    热门问题