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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With