我想将字典中的元素相互比较,并根据一些比较标准删除项目。我希望它高效。我有一个功能可以做到这一点,但它反复复制字典。当然有一个更好的方法:
mydict = {1:5,2:7,3:9,4:9,7:7,8:0,111:43,110:77}
def partial_duplicate_destroyer(mydict,tolerance):
for key1 in mydict.keys():
mydict_copy = mydict.copy()
for key2 in mydict_copy.keys():
if key2 - tolerance < key1 < key2 + tolerance and not(key1 == key2):
del(mydict[key1])
break
return mydict
print partial_duplicate_destroyer(mydict,2)
print partial_duplicate_destroyer(mydict,20)
print partial_duplicate_destroyer(mydict,200)
#correct output:
# {4: 9, 8: 0, 111: 43}
# {8: 0, 111: 43}
# {111: 43}