问题
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