Home > Back-end >  checking for elements in rows and columns of lists of lists without using pandas
checking for elements in rows and columns of lists of lists without using pandas

Time:10-11

If I have a list of lists

matrix = [[2, 3, 1, 2],[1, 2, 3, 2],[3, 3, 1, 2], [2, 2, 3, 3]]

how can I check with a for loop if for example element = 1 is present in each column

CodePudding user response:

Using numpy:

np.any(a==1, 1).all()

>>> a = np.array([[2, 3, 1, 2],[1, 2, 3, 2],[3, 3, 1, 2], [2, 2, 3, 3]])
>>> np.any(a==1, 1).all()
False
>>> a = np.array([[2, 3, 1, 2],[1, 2, 3, 2],[3, 3, 1, 2], [2, 1, 3, 3]])
>>> np.any(a==1, 1).all()
True

CodePudding user response:

Using all, in and a list comprehension:

matrix = [[2, 3, 1, 2], [1, 2, 3, 2], [3, 3, 1, 2], [2, 2, 3, 3]]

valid = all(1 in row for row in matrix)

Or, the verbose way:

matrix = [[2, 3, 1, 2], [1, 2, 3, 2], [3, 3, 1, 2], [2, 2, 3, 3]]

valid = True
for row in matrix:
    if 1 not in row:
        valid = False
        break
  • Related