Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can the symmetric difference between two lists of two-element sublists be obtained?

I have two lists each of which contain two-element lists.

a = [['Adolf', '10'], ['Hermann', '20'], ['Heinrich', '30'], ['Heinrich', '15']]
b = [['Rudolf', '40'], ['Adolf', '50']]

I want to get the 'symmetric difference' of the two lists, based on the 'key' first elements of the sublists.

This 'symmetric difference' would be the following:

c = [['Hermann', '20'], ['Heinrich', '30'], ['Heinrich', '15'], ['Rudolf', '40']]

So, the 'Adolf' entries have been removed because they exist in both lists, while the others, including the 'Rudolf' entry, have been included because they exist not in both lists.

Another example would be the following:

a = [['Adolf', '10'], ['Hermann', '20'], ['Heinrich', '30'], ['Heinrich', '15']]
b = [['Heinrich', '25']]
c = [['Adolf', '10'], ['Hermann', '20']]

I feel that this must be achievable through some clever list comprehensions, but I'm not quite sure how to approach it.

c = [x for x in a_pairs if x not in b_pairs]
like image 320
d3pd Avatar asked Dec 05 '14 17:12

d3pd


People also ask

What is the difference between a list and a sub list?

The data structure we're using in this example is called a list. The difference between a sentence and a list is that the elements of a sentence must be words, whereas the elements of a list can be anything at all: words, #t , procedures, or other lists. (A list that's an element of another list is called a sublist.

Which operator is used for symmetric difference?

Example 3: Symmetric Difference Using ^ Operator In the above example, we have used the ^ operator to find the symmetric difference of A and B and A , B and C . With ^ operator, we can also find the symmetric difference of 3 sets.


1 Answers

You can make a set of names (the first element) from each list, then use ^ which will get the symmetric difference of the sets of names. Then use a list comprehension to iterate over each of the lists and check if the name is in the unique set, then add the results of those two list comprehensions.

def getDifference(x,y):
    symDiff = set(i[0] for i in x) ^ set(i[0] for i in y)
    return [i for i in x if i[0] in symDiff] + [i for i in y if i[0] in symDiff]

First example

>>> a = [['Adolf', '10'], ['Hermann', '20'], ['Heinrich', '30'], ['Heinrich', '15']]
>>> b = [['Rudolf', '40'], ['Adolf', '50']]
>>> getDifference(a,b)
[['Hermann', '20'], ['Heinrich', '30'], ['Heinrich', '15'], ['Rudolf', '40']]

Second example

>>> a = [['Adolf', '10'], ['Hermann', '20'], ['Heinrich', '30'], ['Heinrich', '15']]
>>> b = [['Heinrich', '25']]
>>> getDifference(a,b)
[['Adolf', '10'], ['Hermann', '20']]
like image 152
Cory Kramer Avatar answered Sep 22 '22 08:09

Cory Kramer