Home > Back-end >  Compare two lists and get the indices where the values are different
Compare two lists and get the indices where the values are different

Time:06-29

I would like help with the following situation I have two lists:

Situation 1:

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
b = [0, 1, 2, 3, 5, 5, 6, 7, 8, 9]

I need key output: Key 4 is different

Situation 2:

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
b = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

I need key output: false -> no key is different

Situation 3:

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
b = [0, 9, 2, 3, 4, 5, 6, 7, 3, 9]

I need key output: Key 1 and Key 8 is different

How could I resolve this? My array has 260 keys

CodePudding user response:

You can use a list comprehension with zip, and enumerate to get the indices. Use short-circuiting and the fact that an empty list is falsy to get False:

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
b = [0, 1, 2, 3, 5, 5, 6, 7, 8, 9]

out = [i for i,(e1,e2) in enumerate(zip(a,b)) if e1!=e2] or False

output:

[4]

output for example #2: False

output for example #3: [1, 8]

CodePudding user response:

An approach with itertools.compress. Compare the lists to check difference in values, pass the result of the comparison to compress which will pick-up only the True ones.

from itertools import compress

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
b = [0, 1, 2, 3, 5, 5, 6, 7, 8, 9]

result = tuple(compress(a, map(int.__ne__, a, b)))

if not result:
    print(False)
else:
    print(result)

CodePudding user response:

The current answer is really good, but for an approach which doesn't need zip/enumerate, loop like this:

lista = []
listb = []
unequal_keys = []
for idx in range(len(lista)):
    if lista[idx] != listb[idx]:
        unequal_keys.append(idx)

if unequal_keys == []:
    print(False)
else:
    print(unequal_keys)

I recommend learning new techniques and using build ins like zip and enumerate though. They are much more pythonic and faster!

  • Related