xirururu
xirururu

Reputation: 5508

compare to lists and return the different indices and elements in python

I want to compare to lists and return the different indices and elements.

So I write the following code:

l1 = [1,1,1,1,1]
l2 = [1,2,1,1,3]

ind = []
diff = []

for i in range(len(l1)):
    if l1[i] != l2[i]:
        ind.append(i)
        diff.append([l1[i], l2[i]])

print ind
print diff

# output: 
# [1, 4]
# [[1, 2], [1, 3]]

The code works, but are there any better ways to do that?


Update the Question:

I want to ask for another solutions, for example with the iterator, or ternary expression like [a,b](expression) (Not the easiest way like what I did. I want to exclude it.) Thanks very much for the patient! :)

Upvotes: 0

Views: 137

Answers (3)

Artem Mezhenin
Artem Mezhenin

Reputation: 5757

You can try functional style:

res = filter(lambda (idx, x): x[0] != x[1], enumerate(zip(l1, l2)))
# [(1, (1, 2)), (4, (1, 3))]

to unzip res you can use:

 zip(*res)
 # [(1, 4), ((1, 2), (1, 3))]

Upvotes: 1

halex
halex

Reputation: 16403

An alternative way is the following

>>> l1 = [1,1,1,1,1]
>>> l2 = [1,2,1,1,3]
>>> z = zip(l1,l2)
>>> ind = [i for i, x in enumerate(z) if x[0] != x[1]]
>>> ind
[1, 4]
>>> diff = [z[i] for i in ind]
>>> diff
[(1, 2), (1, 3)]

In Python3 you have to add a call to list around zip.

Upvotes: 2

Cory Kramer
Cory Kramer

Reputation: 118011

You could use a list comprehension to output all the information in a single list.

>>> [[idx, (i,j)] for idx, (i,j) in enumerate(zip(l1, l2)) if i != j]
[[1, (1, 2)], [4, (1, 3)]]

This will produce a list where each element is: [index, (first value, second value)] so all the information regarding a single difference is together.

Upvotes: 2

Related Questions