How to check if a column has different numbers in a list of lists?

I try to identify all columns containing different numbers

for i in range(len(f)): for j in range(len(f[i])): if(f[j][i] != f[j][i+1]): print(f[j][i+1]) 

for example, if the list is f = [[3, 5, 6, 7], [7, 5, 6, 3]] I would like to get col 0 and col 3, but I get: "list index out of range"

Any help would be appreciated.

+5
source share
3 answers

Using zip can provide a better solution:

 for i, (a, b) in enumerate(zip(*f)): if a != b: print i 

zip(*f) gives you:

 In [18]: zip(*f) Out[18]: [(3, 7), (5, 5), (6, 6), (7, 3)] 

And now you can easily compare the "columns".

If you are a guy with one liner:

 [i for i, (a, b) in enumerate(zip(*f)) if a != b] 
+4
source

You have changed the indices. So j is 0,1,2,3 , and when it reaches 2, an error occurs in your if clause. Remember that the first index gives you the subscription index, and the second gives you the index of the item in the sublist.

This correctly gives 0 and 3:

 for i in range(len(f)-1): for j in range(len(f[i])): if(f[i][j] != f[i+1][j]): print(j) 
+1
source

you can use zip :

 f = [[3, 5, 6, 7], [7, 5, 6, 3]] for n, (i, j) in enumerate(zip(*f)): if i != j: print(n) 

expression zip(*f) iterates over the "transposed" version of your list f .

0
source

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


All Articles