找出Python中两个列表之间的区别

2024-04-24 09:02:04 发布

您现在位置:Python中文网/ 问答频道 /正文

如何通过比较对象的一个属性来找出两个对象之间的差异?在

在本例中,如果两个对象的phone属性相同,则称它们相等。在

a1 = {'name':'Tom', 'phone':'1234'}
a2 = {'name':'Dick', 'phone':'1111'}
a3 = {'name':'Harry', 'phone':'3333'}
a = [a1,a2,a3]

b1 = {'name':'Jane', 'phone':'1234'}
b2 = {'name':'Liz', 'phone':'2222'}
b3 = {'name':'Mary', 'phone':'4444'}
b = [b1,b2,b3]

def check(x, y):
    if(x['phone'] == y['phone']):
        return True
    else:
        return False

预期结果应为:

^{pr2}$

我下面的尝试抛出一个错误TypeError: list indices must be integers, not str

[x for x in a if check(a,b)]

Tags: 对象namea2returnif属性checka1
3条回答

此功能:

def minus(list1, list2):
    return [x for x in list1 if x['phone'] not in set(y['phone'] for y in list2)]

给出了以下结果:

^{pr2}$

如果可以更改数据类型,dict可能更好。您可以使用电话号码作为检索姓名的键。在

a = {'1234':'Tom','1111':'Dick','3333':'Harry'}
b = {'1234':'Jane', '2222':'Liz','4444':'Mary'}

def minus(x, y):
    {z:a[z] for z in set(x.keys()) - set(y.keys())}

# {'1111':'Dick','3333':'Harry'}
a_minus_b = minus(a, b)

# {'2222':'Liz','4444':'Mary'}
b_minus_a = minus(b, a)

对于给定的数据结构,您将不得不重复遍历第二个字典列表中的项,这相对效率较低。你关心的是给定的电话号码是否已经存在于第二个字典列表中。重复测试给定值是否存在的最有效的数据结构是set(或者dict,如果您可能需要从电话号码索引回更多信息)。因此,我将按以下方式进行:

a = [a1, a2, a3]
b = [b1, b2, b3]
a_phone_numbers_set = set(d['phone'] for d in a])
b_phone_numbers_set = set(d['phone'] for d in b])
result_A_minus_B = [d for d in a if d['phone'] not in b_phone_numbers_set]
result_B_minus_A = [d for d in b if d['phone'] not in a_phone_numbers_set]

或者,如果我想创建一个函数:

^{pr2}$

或者,您可以使用任意键:

def unmatched_entries(list1, list2, matching_key):
    existing_entries = set(d[matching_key] for d in list2 if matching_key in d)
    return [d for d in list1 if matching_key in d and d[matching_key] not in existing_entries]

该版本总是跳过list1中没有定义请求的键的条目-其他行为是可能的。在

为了匹配简短出现的注释所暗示的多个键,我将使用一组值的元组:

a_match_elements = set((d['phone'], d['email']) for d in a])
result_B_minus_a = [d for d in b if (d['phone'], d['email']) not in a_match_elements]

同样,这可以被推广到处理一系列键。在

相关问题 更多 >