我有一个字典列表:
d_dict = [
{'Abs Diff': 10,'Difference':10, 'Component': 'Local Market', 'Id':'123', 'Name': 'LAT', 'Executor':'AB'},
{'Abs Diff': 20,'Difference':20, 'Component': 'Local Market', 'Id':'123', 'Name': 'LAT', 'Executor':'B'},
{'Abs Diff': 30,'Difference':-30, 'Component': 'Local Market', 'Id':'123', 'Name': 'LAT', 'Executor':'BA'},
{'Abs Diff': 23,'Difference':23, 'Component': 'USD Market', 'Id':'456', 'Name': 'LAT', 'Executor':'CB'},
{'Abs Diff': 25,'Difference':25, 'Component': 'USD Market', 'Id':'456', 'Name': 'LAT', 'Executor':'C'},
{'Abs Diff': 48,'Difference':-48, 'Component': 'USD Market', 'Id':'456', 'Name': 'LAT', 'Executor':'CB'},
{'Abs Diff': 5,'Difference':5, 'Component': 'Price', 'Id':'123', 'Name': 'LAT', 'Executor':'AB'},
{'Abs Diff': 5,'Difference':5, 'Component': 'Price', 'Id':'123', 'Name': 'LAT', 'Executor':'B'},
{'Abs Diff': 10,'Difference':-10, 'Component': 'Price', 'Id':'123', 'Name': 'LAT', 'Executor':'BA'}
]
我的最终目标是拥有一个返回:
的字典result = [
{'Abs Diff': 10,'Difference':10, 'Component': 'Local Market', 'Id':'123', 'Name': 'LAT', 'Executor':'AB', 'Result':'Mismatched Executor'},
{'Abs Diff': 20,'Difference':20, 'Component': 'Local Market', 'Id':'123', 'Name': 'LAT', 'Executor':'B', 'Result':'Mismatched Executor'},
{'Abs Diff': 30,'Difference':-30, 'Component': 'Local Market', 'Id':'123', 'Name': 'LAT', 'Executor':'BA', 'Result':'Mismatched Executor'},
{'Abs Diff': 23,'Difference':23, 'Component': 'USD Market', 'Id':'456', 'Name': 'LAT', 'Executor':'CB', 'Result':'Mismatched Executor'},
{'Abs Diff': 25,'Difference':25, 'Component': 'USD Market', 'Id':'456', 'Name': 'LAT', 'Executor':'C', 'Result':'Mismatched Executor'},
{'Abs Diff': 48,'Difference':-48, 'Component': 'USD Market', 'Id':'456', 'Name': 'LAT', 'Executor':'CB', 'Result':'Mismatched Executor'},
{'Abs Diff': 5,'Difference':5, 'Component': 'Price', 'Id':'123', 'Name': 'LAT', 'Executor':'AB', 'Result':'Mismatched Executor'},
{'Abs Diff': 5,'Difference':5, 'Component': 'Price', 'Id':'123', 'Name': 'LAT', 'Executor':'B', 'Result':'Mismatched Executor'},
{'Abs Diff': 10,'Difference':-10, 'Component': 'Price', 'Id':'123', 'Name': 'LAT', 'Executor':'BA', 'Result':'Mismatched Executor'}
]
我想实现这样一个逻辑:如果Abs Diff大于0,如果组件、id、名称在多个元素之间匹配,如果相同元素之间的差异之和小于1,并且执行器在这些元素之间不同,则返回一个新的键值配对"Result";Mismatched">
我很难想象如何在列表中扫描多个字典并检查匹配的组件、id和名称。
使用一个生成器调用sum()
,该生成器查找符合条件的所有字典。
for i in d_dict:
if i['Abs Diff'] > 0 and
sum(x['Difference'] for x in d_dict
if (x['Component'], x['Id'], x['Name']) == (i['Component'], i['Id'], i['Name']) and x['Executor'] != i['Executor']
) < 1:
i['Result'] = 'Mismatched Executor'
下面是我如何解决这个问题的一个例子
from operator import itemgetter
newdict = []
for i in d_dict:
if(i['Abs Diff'] > 0):
newdict.append(i)
newlist = sorted(newdict, key=itemgetter('Component'))
for i in range(0,len(d_dict)-1):
if(d_dict[i]['Component'] == d_dict[int(i+1)]['Component']):
print("TRUE")