How to look at only the 3rd value in all lists in a list

Question:

I have a list of lists and I want to be able to refer to the 1st, 2nd, 3rd, etc. column in a list of lists. Here is my code for the list:

matrix = [
    [0, 0, 0, 5, 0, 0, 0, 0, 6],
    [8, 0, 0, 0, 4, 7, 5, 0, 3],
    [0, 5, 0, 0, 0, 3, 0, 0, 0],
    [0, 7, 0, 8, 0, 0, 0, 0, 9],
    [0, 0, 0, 0, 1, 0, 0, 0, 0],
    [9, 0, 0, 0, 0, 4, 0, 2, 0],
    [0, 0, 0, 9, 0, 0, 0, 1, 0],
    [7, 0, 8, 3, 2, 0, 0, 0, 5],
    [3, 0, 0, 0, 0, 8, 0, 0, 0],
    ]

I want to be able to say something like:

matrix = [
    [0, 0, 0, 5, 0, 0, 0, 0, 6],
    [8, 0, 0, 0, 4, 7, 5, 0, 3],
    [0, 5, 0, 0, 0, 3, 0, 0, 0],
    [0, 7, 0, 8, 0, 0, 0, 0, 9],
    [0, 0, 0, 0, 1, 0, 0, 0, 0],
    [9, 0, 0, 0, 0, 4, 0, 2, 0],
    [0, 0, 0, 9, 0, 0, 0, 1, 0],
    [7, 0, 8, 3, 2, 0, 0, 0, 5],
    [3, 0, 0, 0, 0, 8, 0, 0, 0],
    ]
if (The fourth column in this matrix does not have any 1's in it):
    (then do something)

I want to know what the python syntax would be for the stuff in parenthesis.

Asked By: chingchong

||

Answers:

The standard way to perform what you asked is to do a list comprehension

if (The fourth column in this matrix does not have any 1’s in it):

translates in:

>>>if not any([1 == row[3] for row in matrix])

However, depending on how often you need to perform this operation, how big is your matrix, etc… you might wish to look into numpy as it is easier (and remarkably faster) to address columns. An example:

>>> import numpy as np
>>> matrix = np.random.randint(0, 10, (5, 5))
>>> matrix
array([[3, 0, 9, 9, 3],
       [5, 7, 7, 7, 6],
       [5, 4, 6, 2, 2],
       [1, 3, 5, 0, 5],
       [3, 9, 7, 8, 6]])
>>> matrix[..., 3]  #fourth column
array([9, 7, 2, 0, 8])
Answered By: mac
if 1 in [row[3] for row in matrix]:
Answered By: Daniel Roseman

Try this:

if all(row[3] != 1 for row in matrix):
    # do something

The row[3] part takes a look at the fourth element of a row, the for row in matrix part looks at all the rows in the matrix – this produces a list with all the fourth elements in all the rows, that is, the whole fourth column. Now if it is true for all the elements in the fourth column that they’re different from one, then the condition is satisfied and you can do what you need inside the if.

A more traditional approach would be:

found_one = False
for i in xrange(len(matrix)):
    if matrix[i][3] == 1:
        found_one = True
        break
if found_one:
    # do something

Here I’m iterating over all the rows (i index) of the fourth column (3 index), and checking if an element is equal to one: if matrix[i][3] == 1:. Notice that the for cycle goes from the 0 index up to the “height” of the matrix minus one, that’s what the xrange(len(matrix)) part says.

Answered By: Óscar López
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.