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]
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.
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.
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']]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With