I need to compare two lists and check if a string from list1 is in list2

Viewed 145

So I will have two lists like this:

list1 = ['p', '-x', 'q123', '-q3']
list2 = ['p56', '-p', '-q123', 'xr']

So lets say if

CASE 1: an item from list1 == 'p' I need to check if '-p' is in list2 or,

CASE 2: an item from list1== '-p' I need to check if 'p' is on list2.

And then delete the element from list1 if any of these cases are triggered, so that I'm only left with elements that only appear in its negative form or only appear in its positive form. Right now I am able to do the CASE 1, but I'm not sure how to do CASE 2.

    
list1 = ['p', '-x', 'q123', '-q3']
list2 = ['p56', '-p', '-q123', 'xr']
new_list1 = list1.copy()
for y in list1:
    for x in list2:
        if x == '-'+y:
            new_list1.remove(y)
      

For these two lists I would be left with only when I handle both cases

new_list1 = ['-q3']

Right now I'm getting this:

new_list1 = ['-x', '-q3']
2 Answers
def toggle(x):
    if x[0] == '-':
        return x[1:]
    else:
        return '-'+x

list1 = ['p', '-x', 'q123', '-q3']
list2 = ['p56', '-p', '-q123', 'x']
new_list1 = list1.copy()
for y in list1:
    for x in list2:
        if x == toggle(y):
            new_list1.remove(y)

this will get you new_list1 == ['-q3']

A more time efficient way:

list1 = ['p', '-x', 'q123', '-q3']
list2 = ['p56', '-p', '-q123', 'x']
toggled_list2 = set(toggle(y) for y in list2)
new_list2 = list(set(list1).difference(toggled_list2))

# new_list2 == ['-q3']
list1 = ['p', '-x', 'q123', '-q3']
list2 = ['p56', '-p', '-q123', 'xr']
    new_list1 = list1.copy()
    for y in list1:
        for x in list2:
            if y == '-'+x:
                new_list1.append(x)` 

Actually you was close.. Try this and use append function. If it work don't forget to upvote

Related