Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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.

like image 998
chingchong Avatar asked Dec 27 '11 15:12

chingchong


People also ask

How do you find elements that are in one list but not another?

To find the elements in one list that are not in the other: Use the set() class to convert the first list to a set object. Use the difference() method to get the elements in the set that are not in the list.

How do you find the index of a specific element in a list Python?

To find the index of a list element in Python, use the built-in index() method. To find the index of a character in a string, use the index() method on the string. This is the quick answer.

How do I get the first element of a list in Python?

List slicing. List slicing is another method in which we directly refer to the positions of elements using the slicing technique using colons. The first element is accessed by using blank value before the first colon and the last element is accessed by specifying the len() with -1 as the input.


1 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])
like image 70
mac Avatar answered Sep 20 '22 01:09

mac