tibetish
tibetish

Reputation: 119

Comparing between entries in a list of lists using correct indexes

I have a list of lists and I'm trying to compare the entries in an inner list to the others. eg: the list is my_list = [[4,6,4,3], [4,5,5,3], [4,1,1,3]] The output I wish to get is [4,'x','x',3] That is, if the entry in the i index in an inner list is the same across all inner lists I return the entry else I return 'x'.
I have trouble with the indexes in my code since for the i=2 round of the loop I get rows[4][j] and this is out of index. I'm generally not sure about the outer loop here or how to fix the indexes in the condition.

def my_function(my_list):
    lst = []
    for i, entry in enumerate(my_list):
        for j, elem in enumerate(entry):
            if my_list[i][j] == my_list[i+1][j] and my_list[i+1][j] == my_list[i+2][j]:
                lst.append(my_lists[i][j])
            else:
                lst.append('x')
    return lst

Upvotes: 3

Views: 770

Answers (4)

Mehrdad Pedramfar
Mehrdad Pedramfar

Reputation: 11073

You can also use all for checking this:

[i[0] if all(j == i[0] for j in i) else 'X' for i in(zip(*my_list))]

or:

[i[0] if all(map(lambda j: j == i[0], i )) else 'X' for i in(zip(*my_list))]

You can also extend an item to see:

[i[0] if [i[0]]*len(i) == list(i) else 'X' for i in(zip(*my_list))]

But I think the best way is to use set:

[i[0] if len(set(i))==1 else 'X' for i in(zip(*my_list))] 

Upvotes: 1

Shivam Gupta
Shivam Gupta

Reputation: 201

You can use this simple python code.

my_list = [[4,6,4,3], [4,5,5,3], [4,1,1,3]]
li = []
for i, j, k in zip(*my_list):
    val = i if i == j == k else 'x'
    li.append(val)
print(li)

OUTPUT :

[4, 'x', 'x', 3]

Upvotes: 2

Georgina Skibinski
Georgina Skibinski

Reputation: 13387

You can use numpy + list comprehension for that purpose:

import numpy as np

my_list = np.array([[4,6,4,3], [4,5,5,3], [4,1,1,3]])

res=['x' if (len(set(my_list[:,i]))>1) else list(set(my_list[:,i]))[0] for i in range(my_list.shape[1])]

Output:

[4, 'x', 'x', 3]

And to fix your code (I'm not sure what you meant by your if statement)

def my_function(my_list):
    lst = my_list[0]
    for i, entry in enumerate(my_list):
        for j, elem in enumerate(entry):
            if my_list[i][j]==lst[j]:
                lst[j]=my_list[i][j]
            else:
                lst[j]='x'
    return lst

Upvotes: 3

Thierry Lathuille
Thierry Lathuille

Reputation: 24232

You should avoid manipulating indices as much as possible. To iterate on multiple lists, use zip.

To test if all values in a list are equal, you can create a set, and check if it contains only one value.

my_list = [[4,6,4,3], [4,5,5,3], [4,1,1,3]]
out = [zipped[0] if len(set(zipped)) == 1 else 'X' for zipped in zip(*my_list)]
print(out)
# [4, 'X', 'X', 3]

Upvotes: 4

Related Questions