如何显示两个词典列表之间的差异

问题描述 投票:0回答:1

我有这两个列表:

list1 = [
    {'name': 'one', 'email': '[email protected]', 'phone': '111'},
    {'name': 'two', 'email': '[email protected]', 'phone': '111'},
    {'name': 'three', 'email': '[email protected]', 'phone': '333'},
    {'name': 'four', 'email': '[email protected]', 'phone': '444'},
]
list2 = [
    {'first_name': 'three', 'email': '[email protected]', 'phone_number': '333'},
    {'first_name': 'four', 'email': '[email protected]', 'phone_number': '444'},
    {'first_name': 'five', 'email': '[email protected]', 'phone_number': '555'},
]

我知道如何根据键查找两个列表之间的差异:

list1_only = list(set([x['phone'] for x in list1]) - set([x['phone_number'] for x in list2]))

但是当前的输出是:

['111']

但是我最终会得到这个输出:

[
    {'name': 'one', 'email': '[email protected]', 'phone': '111'},
    {'name': 'two', 'email': '[email protected]', 'phone': '111'}
]

我知道这种方式,但我认为(并且确信)有更好的方法:

for l in list1:
    for d in diff:
        if d == l['phone']:
            print(l)

我读了其他问题,例如this,但它打印了整个列表(而不是差值):

[x for x in list2 if x['phone_number'] not in list1]

您能帮我解决这个问题吗?

是否有任何一行方法可以替换为

list1_only = list(set([x['phone'] for x in list1]) - set([x['phone_number'] for x in list2]))

python
1个回答
0
投票

我看到的问题是

list2
中的键与
list1
中的键不同,所以我将映射它们以进行比较:

list1 = [
    {'name': 'one', 'email': '[email protected]', 'phone': '111'},
    {'name': 'two', 'email': '[email protected]', 'phone': '111'},
    {'name': 'three', 'email': '[email protected]', 'phone': '333'},
    {'name': 'four', 'email': '[email protected]', 'phone': '444'},
]
list2 = [
    {'first_name': 'three', 'email': '[email protected]', 'phone_number': '333'},
    {'first_name': 'four', 'email': '[email protected]', 'phone_number': '444'},
    {'first_name': 'five', 'email': '[email protected]', 'phone_number': '555'},
]


mapped_names = lambda dct: {'first_name':   dct['name'],
                            'email':        dct['email'],
                            'phone_number': dct['phone']}

diff = [dct for dct in list1 if mapped_names(dct) not in list2]
print(diff)
# >>> [{'name': 'one', 'email': '[email protected]', 'phone': '111'},
#      {'name': 'two', 'email': '[email protected]', 'phone': '111'}]
© www.soinside.com 2019 - 2024. All rights reserved.