How to see only the third value in all lists in the list

I have a list of lists and I want to be able to reference column 1, 2, 3, etc. in the 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 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 in it):
    (then do something)

I want to know what will be the python syntax for the contents in brackets.

+5
source share
3 answers

Try the following:

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

The part row[3]considers the fourth element of the row, the part for row in matrixlooks through all the rows in the matrix - this creates a list with all the fourth elements in all rows, i.e. entire fourth column. Now, if this is true for all the elements in the fourth column, they are different from one, then the condition is satisfied, and you can do what you need inside if.

:

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

(i index) (3 index) , : if matrix[i][3] == 1:. , for 0 "" , xrange(len(matrix)).

+2

, ,

if ( 1):

:

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

, , , .., numpy, ( ) . :

>>> 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])
+4
if 1 in [row[3] for row in matrix]:
0
source

All Articles