Comparison of content in matrices

Asked

Viewed 38 times

0

Have some python solution to use something similar to np.all in arrays that are filled with strings or ints?

Below an example of what I wish, perform the comparison of a row of the matrix to verify that all elements are equal.

tab2 = [
    ['X','O','X'],
    ['X','X','X'],
    ['O','O','O'],
]



for i in range(0, len(tab2)):        
    tab = tab2[:i]
    x = np.all(tab)
    print (x)
    if (x):
        break
    else: 
        tab = 0

2 answers

2

One solution is to use the builtin function all to check that all line elements are equal to the first:

tab2 = [
    ['X','O','X'],
    ['X','X','X'],
    ['O','O','O'],
]

def is_equal(row):
    return all([row[0]==row[i] for i in range(len(row))])

print([is_equal(r) for r in tab2])

Returns:

[False, True, True]

See also the function any

0


I used the following solution:

for i in range (0, len(tab)):
    if (tab[i].count('X') == len(tab)):
        print (i)

Basically this code checks if the amount of "X" in the vector is equal to the size of the vector, the print is only a test.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.