compare two lists and print out unequal elements

﹥>﹥吖頭↗ 提交于 2019-12-11 03:07:38

问题


I have two lists in the following format:

list1 = ['A','B','C','D']
list2 = [('A',1),('B',2),('C',3)]

I want to compare the two lists and print out a third list which will have those elements present in list1 but not in list2 and I want to compare only the list2[i][0] elements.

I tried the below code:

fin = [i for i in list1 if i not in list2]

But it prints all the elements in list1. I want the output in the above case to be :

fin = ['D']

Could somebody please suggest how to do that? Also, I do not want to convert my 2D array list2 to 1D array.


回答1:


Use the set difference.

set(list1) - set(i[0] for i in list2)



回答2:


You can do this as well (you need to compare i with the first element of each tuple in list2):

fin = [i for i in list1 if i not in map(lambda(x,_):x,list2)]



回答3:


How about nested comprehensions:

fin = [a for a in list1 if a not in [b for b,_ in list2]]


来源:https://stackoverflow.com/questions/17624407/compare-two-lists-and-print-out-unequal-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!