Skip to main content
 首页 » 编程设计

python比较两个列表之间的差异

2025年05月04日11zengkefu

我有两个这样的列表:

newList = ( 
    (1546, 'John'), 
    (8794, 'Michael'), 
    (892416, 'Dave'), 
    (456789, 'Lucy'), 
    ) 
 
oldList = ( 
    (1546, 'John'), 
    (8794, 'Michael'), 
    (892416, 'Dave'), 
    (246456, 'Alexander') 
    ) 

我想要一个比较两个列表的函数。它会是这样的:

def compare(new, old): 
    print('Alexander is not anymore in the new list !') 
    print('Lucy is new !') 
    return newList  

我想比较每个人的唯一身份。

编辑:结果将是我的函数比较。它打印差异。 我不知道如何开始

请您参考如下方法:

您可以将列表转换为集合并取差

n = set(l[1] for l in newList) 
o = set(l[1] for l in oldList) 
print n - o # set(['Lucy']) 
print o - n # set(['Alexander'])