Rakesh Adhikesavan
Rakesh Adhikesavan

Reputation: 12826

How to count the difference between two nested lists in Python?

If I had the two following lists with tuples in the form of (x,y):

 [(a,1),(b,2),(c,7),(d,1)]
 [(a,3),(b,2),(c,7),(d,8)]

I want to count the number of differences with respect to 'y' value for corresponding 'x' values. In the above case, the answer is 2

(a,1) doesn't match with (a,3)

(d,1) doesn't match with (d,8)

EDIT: This is not a duplicate, the position of the elements matter. I want to check if element 1 in list 1 is same as element 1 in list 2 and so on.

Upvotes: 0

Views: 277

Answers (2)

Shawn Mehan
Shawn Mehan

Reputation: 4578

Another method is

x = [("a", 1) ,("b", 2), ("c", 7), ("d", 1)]
y = [("a", 3), ("b", 2), ("c", 7), ("d", 8)]
count = len(set(x).intersection(y))

Upvotes: 0

Kasravnd
Kasravnd

Reputation: 107347

You can use zip function and a generator expression within sum function :

count=sum(i!=j for i,j in zip(list1,list2))

Upvotes: 2

Related Questions