我想根据以下规则清理字典列表:
1) 字典列表已经排序,所以优先选择较早的字典。
2)在较低的dicts中,如果['name']
和 ['code']
字符串值与列表中较高位置的任何字典的相同键值匹配,如果 int(['cost'])
的差异的绝对值|在这两个命令之间是 < 2
;然后该字典被假定为先前字典的副本,并从列表中删除。
这是字典列表中的一个字典:
{
'name':"ItemName",
'code':"AAHFGW4S",
'from':"NDLS",
'to':"BCT",
'cost':str(29.95)
}
像这样删除重复项的最佳方法是什么?
最佳答案
可能有更 pythonic 的方式来做到这一点,但这是基本的伪代码:
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)
关于python - 从字典列表中删除具有近乎重复值的字典 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5668366/