你可以用
itertools.groupby
:
from itertools import groupby
match_on = ['s_source_zone', 's_destination_zone', 'Services',
's_logical_system', 's_virtual_router']
groupfunc = lambda x: [x[match] for match in match_on]
result = []
for (source, dest, service, log, virt), group in groupby(input_, groupfunc):
group_ = tuple(group) # otherwise iterator goes bye-bye
res = {'Destination IP': ', '.join(d['Destination IP'] for d in group_),
'Services': service,
'Source IP': ', '.join(d['Source IP'] for d in group_),
's_destination_zone': dest,
's_logical_system': log,
's_matched_route': ', '.join(d['s_matched_route'] for d in group_),
's_source_zone': source,
's_virtual_router': virt}
result.append(res)
从您的示例可以推断出,实际上有5个键/值对需要匹配。(否则,您可能会以某种方式组合重复/相同的值,但您没有这样做。)
此处的lambda funct匹配输入中的字典,基于它们具有中5个键的等效值的交点
match_on
. 所有匹配的词典都被放入
group
,这是一个
itertools._grouper
迭代器。