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]]
Not sure if there is a nice function for this, but the "manual" way to do it isn't difficult:
i guess you'll have to convert your lists to sets:
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:
map
is a functional programming command that applies the function in the first argument (in this case thetuple
function) 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_set
is 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
filter
command andlambda
functions. (You have to test both ways and combine).By using set comprehensions, you can make it a one-liner. If you want:
to get a set of tuples, then:
Or to get a list of tuples, then:
Or to get a list of lists (if you really want), then:
PS: I read here: https://stackoverflow.com/a/10973817/4900095 that map() function is not a pythonic way to do things.
Old question but here's a solution I use for returning unique elements not found in both lists.
I use this for comparing the values returned from a database and the values generated by a directory crawler package. I didn't like the other solutions I found because many of them could not dynamically handle both flat lists and nested lists.