What is the easiest way to compare the 2 lists/sets and output the differences? Are there any built in functions that will help me compare nested lists/sets?
Inputs:
First_list = [['Test.doc', '1a1a1a', 1111],
['Test2.doc', '2b2b2b', 2222],
['Test3.doc', '3c3c3c', 3333]
]
Secnd_list = [['Test.doc', '1a1a1a', 1111],
['Test2.doc', '2b2b2b', 2222],
['Test3.doc', '8p8p8p', 9999],
['Test4.doc', '4d4d4d', 4444]]
Expected Output:
Differences = [['Test3.doc', '3c3c3c', 3333],
['Test3.doc', '8p8p8p', 9999],
['Test4.doc', '4d4d4d', 4444]]
So you want the difference between two lists of items.
First I’d turn each list of lists into a list of tuples, so as tuples are hashable (lists are not) so you can convert your list of tuples into a set of tuples:
Then you can make sets:
EDIT (suggested by sdolan): You could have done the last two steps for each list in a one-liner:
Note:
mapis a functional programming command that applies the function in the first argument (in this case thetuplefunction) to each item in the second argument (which in our case is a list of lists).and find the symmetric difference between the sets:
Note
first_set ^ secnd_setis equivalent tosymmetric_difference.Also if you don’t want to use sets (e.g., using python 2.2), its quite straightforward to do. E.g., with list comprehensions:
or with the functional
filtercommand andlambdafunctions. (You have to test both ways and combine).