简体   繁体   中英

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

I used: third_list = list(set(second_list) ^ set(first_list)) but it return me: 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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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