Reputation: 458
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)
Upvotes: 2
Views: 95
Reputation: 882
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)
Upvotes: 4
Reputation: 7206
listA = ['E','F','G']
listB = ['E','G']
use list comprehension
diff2 = [y for y in listA if y not in listB]
print (diff2)
output: ['F']
or
diff1=[]
for item in listA:
if item not in listB:
diff1.append(item)
print (diff1)
output: ['F']
Upvotes: 1
Reputation: 82929
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'}
Upvotes: 3
Reputation: 31
Intersection is a common part of sets. If you want a difference of sets just use... a difference method. E.g.:
list(set(listA) - set(listB))
or:
list(set(listA).difference(set(listB)))
Upvotes: 1