Given two lists:
listA = ['A' , 'B' , 'C, D' , 'E, F, G', 'H' , 'I']
listB = ['C' , 'E, G' , 'A' , 'B' , 'I']
I want to compare each element and highlight the differences where it is applicable.
listA['E,F,G'] and listB['E,G'].
The difference would be ['F']
There are several differences between the individual list elements and ideally would like to flag them all. Is this possible with python? Is the below thinking correct?
set(listA).intersection(listB)
What you are looking for is symmetric difference. In python you can achieve it by using symmetric_difference function or using short hand s ^ t.
s.symmetric_difference(t)
This will give you the difference elements. Now, what you can do is
def split_words(element):
if len(element) > 1:
element = element.split(',')
return element
result = []
for e1, e2 in zip(sorted(list_a), sorted(list_b)):
if e1 not in list_b:
e1 = split_words(e1)
e2 = split_words(e2)
diff = set(e1) ^ set(e2)
result.append(diff)
From comments, it seems like you want to "unpack" the nested pseudo-string-lists before calculating the difference. You could define a simple helper function for that.
>>> listA = ['A' , 'B' , 'C, D' , 'E, F, G', 'H' , 'I']
>>> listB = ['C' , 'E, G' , 'A' , 'B' , 'I']
>>> elements = lambda s: set(x for y in s for x in y.split(", "))
>>> elements(listA)
{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'}
Then, you can use set operations like -, ^, &, or | to get what you want.
>>> elements(listA) - elements(listB) # difference
{'D', 'F', 'H'}
>>> elements(listA) ^ elements(listB) # sym. diff.
{'D', 'F', 'H'}
>>> elements(listA) & elements(listB) # intersection
{'A', 'B', 'C', 'E', 'G', 'I'}
>>> elements(listA) | elements(listB) # union
{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'}
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