user1310420
user1310420

Reputation:

Python matrices

I want to make a matrix in python with three columns per row and to be able to index them by any one of the rows. Each value in the matrix is unique.

From what I can tell, I can set up a matrix like:

matrix = [["username", "name", "password"], ["username2","name2","password2"]...]

However, I don't know how to access an element from it.

Thanks

Upvotes: 1

Views: 6159

Answers (3)

unutbu
unutbu

Reputation: 879083

You could use a list of lists:

In [64]: matrix = [["username", "name", "password"],["username2","name2","password2"]]

In [65]: matrix
Out[65]: [['username', 'name', 'password'], ['username2', 'name2', 'password2']]

Access the first row (since Python uses 0-based indexing):

In [66]: matrix[0]
Out[66]: ['username', 'name', 'password']

Access the second item in the first row:

In [67]: matrix[0][1]
Out[67]: 'name'

A list of lists is not a good choice of data structure if you want to look up names based on usernames. To do that, you'd have to loop through (potentially) all the items in the matrix to find the item whose username matches the specified username. The time to complete the search would grow linearly with the number of rows in the matrix.

In contrast, dicts have, on average, constant-time lookups no matter how many keys are in the dict. So, for example, if you were to define

matrix = {
    'capitano': {'name':'Othello', 'password':'desi123'}
    'thewife': {'name':'Desdemona', 'password':'3apples'}
    }

(where 'capitano' and 'thewife' are usernames)

then to find the name of the person with username 'capitano', you would use

matrix['capitano']['name']

and Python would return 'Othello'.


Functions are first-class objects in Python: You can pass them around as objects, just as you would a number or a string. So, for example, you can store a function as the value in a dict's (key, value) pair:

from __future__ import print_function    
matrix = {'hello': {'action': lambda: print('hello')} }

Then to call the function, (note the parentheses):

matrix['hello']['action']()
# hello

Upvotes: 2

dckrooney
dckrooney

Reputation: 3121

What you've demonstrated is a matrix which is comprised of a list of lists.

You can access the elements by using the index of the row and column:

>>> matrix[0] # This will return the 0th row
['username', 'name', 'password']
>>> matrix[0][1] # This will return the element from row 0, col 1
'name'

Upvotes: 1

Mr Fooz
Mr Fooz

Reputation: 111846

If you're able to install a library, consider using numpy. It has a rich set of tools for efficiently handling rectangular multidimensional arrays and slicing them.

Upvotes: 3

Related Questions