Python矩阵

2024-04-20 16:16:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在python中创建一个每行有三列的矩阵,并能够按任意一行对它们进行索引。矩阵中的每个值都是唯一的。

据我所知,我可以建立一个矩阵,比如:

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

但是,我不知道如何从中访问元素。

谢谢


Tags: name元素username矩阵passwordmatrixname2password2
3条回答

您可以使用列表:

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

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

访问第一行(因为Python使用基于0的索引):

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

访问第一行中的第二项:

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

列表不是数据结构的好选择 如果要根据用户名查找名称。 要做到这一点,您必须(潜在地)遍历matrix中的所有项 查找其用户名与指定用户名匹配的项。 完成搜索的时间将随着矩阵中的行数线性增长。

相比之下,不管有多少,dict的平均值都是constant-time lookups 键在dict中。例如,如果要定义

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

(其中'capitano''thewife'是用户名)

然后要查找用户名为'capitano'的人的姓名,可以使用

matrix['capitano']['name']

Python将返回'Othello'


函数是Python中的一级对象:您可以将它们作为对象传递,就像传递数字或字符串一样。因此,例如,可以将函数存储为dict(key,value)对中的值:

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

然后调用函数(注意括号):

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

如果能够安装库,请考虑使用numpy。它有一套丰富的工具来有效地处理矩形多维数组并对它们进行切片。

你演示的是一个矩阵,它由一个列表组成。

可以使用行和列的索引访问元素:

>>> 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'

相关问题 更多 >