简体   繁体   English

如何确定列表之间的差异?

[英]How to determine the difference between the lists?

I have two lists: 我有两个清单:

first_list = [('A', 'Name A'), ('B', 'Name B'), ('C', 'Other Name')]
second_list = [('A', 'Name A'), ('B', 'Name B'), ('C', 'Name C'), ('D', 'Name D')]

I want such list: third_list = [('D', 'Name D')] 我想要这样的列表: third_list = [('D', 'Name D')]

I used: third_list = list(set(second_list) ^ set(first_list)) but it return me: third_list = [('C', 'Name C'), ('D', 'Name D')] . 我用过: third_list = list(set(second_list) ^ set(first_list))但它返回了我: third_list = [('C', 'Name C'), ('D', 'Name D')]

So as you can see I want list where first items of tuples are different. 因此,如您所见,我想列出元组的第一项不同的地方。 ('C', 'Other Name') and ('C', 'Name C') must be the same cause there first items in tuples are the same. ('C', 'Other Name')('C', 'Name C')必须相同,因为元组中的第一项相同。

Check online demo 查看在线演示

first_list = [('A', 'Name A'), ('B', 'Name B'), ('C', 'Other Name')]
second_list = [('A', 'Name A'), ('B', 'Name B'), ('C', 'Name C'), ('D', 'Name D')]

first_dict = dict(first_list)
second_dict = dict(second_list)
value = { k : second_dict[k] for k in set(second_dict) - set(first_dict) }
print(value)

This will do the job: 这将完成工作:

first_second = [('A', 'Name A'), ('B', 'Name B'), ('C', 'Other Name')]
second_second = [('A', 'Name A'), ('B', 'Name B'), ('C', 'Name C'), ('D', 'Name D')]
d_one=dict(first_second)
d_two=dict(second_second)
res=[(i,j) for i,j in d_two.items() if i in set(d_two).symmetric_difference(set(d_one)) ]

Then res is 然后res

[('D', 'Name D')]
[x for x in second_list if x[0] not in dict(first_list)]

[('D', 'Name D')]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM