Go through multiple lists at the same time and record the difference in values

Consider an API that returns four lists as output. Let us consider the conclusion 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, equal or not.

Lists are equal only if elements and indices match. For example, from the above lists, a and b are equal. But a and c not equal.

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

To compare and get the differences in the two lists, I wrote the code below.

 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 the question is how to achieve this for all four lists?

+6
source share
3 answers

You can use zip to repeat each list at the same time and compare the values ​​for each index. In the example below, I compare the value of list a with the rest of the 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 
+4
source

From the comment:

How to find in which list we have different meanings?

 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 

Conclusion (inappropriate lists):

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

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

+1
source

Set up the list mylist = [a, b, c,d] Then run a loop checking which ones are equal and which are not equal.

 for i in range(len(mylist)-1) for j in range(i+1, len(mylist)) # Check mylist[i] agaist mylist[j] and report results 

For example, this will check a against b, c and d
b vs c and d
c vs d

0
source

Source: https://habr.com/ru/post/1014165/


All Articles