Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simultaneously iterate over multiple list and capture difference in values

Consider API returning four lists as output. Let's consider output as

a = [1,2,3,4]
b = [1,2,3,4]
c = [1,2,4,3]
d = [1,2,3,5]

Now, first we want to compare these lists are equal or not.

Lists are equal only if elements and there indexes matches. For example, from above lists, a and b are equal. But a and c are not equal.

If the lists are not equal, then output is expected as: this element at this index in this list is not same as other.

For comparing and getting differences of two lists, I have written below code.

for i in range(len(a)):
    if a[i] != c[i]:
        print "Expected value at ",i," is ",a[i]
        print "But got value ",c[i],"in second list"    

Now question is how to achieve this for all four above lists?

like image 539
Dinesh Pundkar Avatar asked Jan 17 '17 19:01

Dinesh Pundkar


2 Answers

You may use zip to iterate over each list simultaneously and compare the value at each index. In the below example, I am comparing the value of list a with remaining lists.

a = [1,2,3,4]
b = [1,2,3,4]
c = [1,2,4,3]
d = [1,2,3,5]

for i, x in enumerate(zip(a, b, c, d)):
    print('--------- Index: {}'.format(i))
    base = x[0]
    for j, y in enumerate(x[1:], 2):
        if base!=y:
            print('{} not equal to {} : --> List {}'.format(base, y, j))

which prints:

--------- Index: 0
--------- Index: 1
--------- Index: 2
3 not equal to 4 : --> List 3
--------- Index: 3
4 not equal to 3 : --> List 3
4 not equal to 5 : --> List 4
like image 97
Moinuddin Quadri Avatar answered Oct 19 '22 17:10

Moinuddin Quadri


From the comment:

How to find in which list we have different value?

import collections as ct

counter = ct.Counter(map(tuple, [a,b,c,d]))                # make hashable keys w/tuples
base = counter.most_common(1)[0][0]                        # find most frequent sequence
[list(seq) for seq in counter if seq != base]              # filter uncommon sequences

Output (the non-matching lists):

[[1, 2, 4, 3], [1, 2, 3, 5]]

We collect all similar sequences as keys in a collections.Counter. If all sequences match, there should only be one entry in the Counter dictionary. Otherwise, filter the remaining sequences.

like image 39
pylang Avatar answered Oct 19 '22 17:10

pylang