我想根据以下规则清理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)
}
像这样删除重复项的最佳方法是什么?在
可能还有一种更像Python的方法来实现这一点,但这是基本的伪代码:
这是一个复杂的问题,但我认为这样的方法会奏效:
既然你说成本是整数,那么你可以使用:
下面是一种不那么复杂的方法来计算差异:
^{pr2}$这两种解决方案都避免重新扫描每个项目的整个列表。毕竟,只有在
(name, code)
相等的情况下,成本才会变得有趣,所以您可以使用字典快速查找所有候选项。在相关问题 更多 >
编程相关推荐