How to check if all elements in a 2D list are the same?

I need help checking if all the elements in a two-dimensional list match (in this case, I check if they are all equal to one).

I made a function allOnes(L)that checks if all elements are 1 in a 1D array. I used the all () function as follows:

def allOnes(L):
    """Tests to see if the numbers in the list L are all 1's
    """
    return all(x == 1 for x in L)

Now I need to check if everything is all 2D-list 1. I would like to see the function returns True The allOnes2d, when it checks the list as follows: [[1,1,1], [1,1,1], [1,1,1]]. Is this possible with help all()?

+3
source share
4 answers
def allOnes2d(L):
    return all(allOnes(a) for a in L)

, itertools.chain, N- , allOnes. ( Lattyware)

+4

numpy.

import numpy
table= numpy.array([[1,1,1], [1,1,1], [1,1,1]])
print numpy.all( table == 1 )
+3

While use all()and your specific function is a good way to do this, you can also explore this alternative

>>> from itertools import chain
>>> sum(1 for e in chain(*[[1,1,1], [1,1,1], [1,1,1]]) if e!= 1)
0

or you can also call allOnesafter expanding the list throughitertools.chain

>>> allOnes(chain(*[[1,1,1], [1,1,1], [1,1,1]]))
True
>>> 
+1
source

I like recursion for this kind of thing:

from collections import Iterable
def allOnes(I):
    if isinstance(I, Iterable):
        return all(allOnes(i) for i in I)
    else:
        return I == 1

example:

>>> L = [[1,1,1], (1,1,1), 1]
>>> allOnes(L)
True
>>> L = [[1,1,1], (1,0,1), 1]
>>> allOnes(L)
False
+1
source

All Articles