I have two lists. X list is bigger, Y list is smaller.
I want to find elements from Y list that are different from elements in X list, but also elements that are not part of the any element in X list. Also, elements from X list can not be part of elements in Y list.
For example A A is part of A A B, AA B is part of AA BB but A C A, C BB, S are not part of any element in Y.
Also, you will see that X has C A and Y has CC A, that is not allowed.
X = ["A A B", "A B C", "AA BB", "BB C A", "A C B", "BB C A", "X", "C A"]
Y = ["A A", "A C A", "AA B", "C BB", "S", "CC A"]
I have tried something like this, with different place of else but it does not work good
for x in X:
for y in Y:
if x in y or y in x:
continue
else:
print(y)
Requested result:
C BB
S
>Solution :
- Go over each element in
Y. - For each one, go over each element in
X. - If any of them contain each other in any direction –
break. - Else, take the item:
X = ["A A B", "A B C", "AA BB", "BB C A", "A C B", "BB C A", "X", "C A"]
Y = ["A A", "A C A", "AA B", "C BB", "S", "CC A"]
for y in Y:
for x in X:
if y in x or x in y:
break
else:
print(y)
Gives:
C BB
S
This uses the for/else construct which means that the else part will only be executed if the loop executed to exhaustion, without breaking.
Or, the shorter way by using any:
for y in Y:
if not any(y in x or x in y for x in X):
print(y)
or, by De Morgan’s laws we can use all:
for y in Y:
if all(y not in x and x not in y for x in X):
print(y)