old = [('ver','1121'),('sign','89'),('address','A45'),('type','00')]
new = [('ver','1121'),('sign','89'),('type','01')]
我需要根据元组的第一个元素将新列表与旧列表进行比较,并显示新列表中的任何元素之间的差异,以便输出应如下所示:
Match : ver = 1121
Match : sign = 89
Mismatch : type = 01 (old : 00)
我可以通过下面的列表理解得到所有匹配的元组,但不能超越它.
my_list = [(a,b) for (a,b) in new for (c,d) in old if ((a==c) and (b==d))]
print( my_list)
请建议我这样做的方法.
编辑
我很抱歉没有明确我的问题,我没有提到一件事,列表中的键可以重复,这意味着列表可以是:
old = [('ver','1121'),('sign','89'),('address','A45'),('type','00'),('ver','sorry')]
new = [('ver','1121'),('sign','89'),('type','01'),('ver','sorry)]
UPDATE
感谢@holdenweb,我对他的代码进行了一些更改,这似乎提供了预期的输出,如果有任何缺陷,请建议.
old = [('ver','1121'),('sign','89'),('address','A45'),('type','00'),('ver','works?')]
new = [('ver','1121'),('sign','89'),('type','01'),('ver','This')]
formatter = "{:12}: {:8} = {}".format
newfmter = "{} (old : {})".format
kv_old = []
for i,(kn, vn) in enumerate(new):
vo = [(j,(ko,vo)) for j,(ko, vo) in enumerate(old) if (ko==kn) ]
for idx,(key,val) in vo:
if idx >=i:
kv_old = [key,val]
break;
if kv_old[1]==vn:
print(formatter("Match", kv_old[0], kv_old[1]))
else:
print(formatter("Mismatch", kn, newfmter(vn, kv_old[1])))
解决方法:
你可以使用一套:
>>> old = [('ver','1121'),('sign','89'),('address','A45'),('type','00')]
>>> new = [('ver','1121'),('sign','89'),('type','01')]
>>> print('no longer there:', set(old) - set(new))
no longer there: {('type', '00'), ('address', 'A45')}
>>> print('newly added:', set(new) - set(old))
newly added: {('type', '01')}
>>> print('still there:', set(old) & set(new))
still there: {('sign', '89'), ('ver', '1121')}