python - 比较两个元组列表

标签 python list tuples list-comprehension

old = [('ver','1121'),('sign','89'),('address','A45'),('type','00')]
new = [('ver','1121'),('sign','89'),('type','01')]

我需要比较new列表反对 old一个基于元组的第一个元素,并显示任何元素之间的差异new list 有,所以输出应该是这样的:
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)]

更新

感谢@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])))

最佳答案

一个 set是查找此类不匹配项的绝佳工具:

>>> 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')}

关于python - 比较两个元组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43256677/

相关文章:

python - 如何对列表列表进行排序并仅保留每个第一个元素的最大第二个元素?

python - 使用 Python 进行元组和列表操作。缩短元组生成

python - 以表格格式漂亮地打印列表

python - 删除 Pandas Dataframe 中按其他列分组的列中频率最低的行

c# - 如何在 C# 中将 Object 转换为 List<string>?

python - 统计groupby中每年出现的次数

python - python 中奇怪的二维列表行为

dictionary - Julia : construct Dictionary with tuple values

python - pip 安装最新的依赖版本

python - 仅使用 4 个运算符(包括两个加法和两个减法符号)的数字 1-9 的可能组合