[英]Create python 2d array indexed by string
(I'm not too great at python, so forgive me if this is a stupid question) (我不太擅长使用python,因此如果这是一个愚蠢的问题,请原谅我)
So I want to create a data structure that represents this - 所以我想创建一个表示这种情况的数据结构-
word1 word2
word3 1 2
word4 3 4
Right now I've tried doing something like this - 现在我已经尝试做这样的事情-
self.table = [][]
but this is giving me an invalid syntax error(I guess because I haven't initialized the arrays?). 但这给了我一个无效的语法错误(我想是因为我还没有初始化数组?)。 However, even if I were to use this I wouldn't be able to use it because I don't know how large my x and y dimension is(it seems like there would be an array out of index exception).
但是,即使我要使用它,也将无法使用它,因为我不知道我的x和y尺寸有多大(似乎会有索引异常数组)。
Should I be using a double dictionary? 我应该使用双重字典吗? What should I be using?
我应该使用什么?
The idea is to create a dictionary, which maps the strings to the indeces. 这个想法是创建一个字典,将字符串映射到索引。 In the following there's a little class which overloads the '[ ]'-operator:
在下面的代码中,有一个小类可以重载'[]'运算符:
class ArrayStrIdx:
""" 2D Array with string as Indeces
Usage Example::
AA = ArrayStrIdx()
AA["word1", "word3"] = 99
print(AA["word2", "word5"])
"""
cols ="word1 word2"
rows ="word3 word4 word5"
dd = [[10,11,12],[20,21,22]] # data
def __init__(self):
""" Constructor builds dicts for indexes"""
self.ri = dict([(w,i) for i,w in enumerate(self.rows.split())])
self.ci = dict([(w,i) for i,w in enumerate(self.cols.split())])
def _parsekey(self, key):
""" Convert index key to indeces for ``self.dd`` """
w0, w1 = key[0], key[1]
return self.ci[w0], self.ri[w1]
def __getitem__(self, key):
""" overload [] operator - get() method"""
i0, i1 = self._parsekey(key)
return self.dd[i0][i1]
def __setitem__(self, key, value):
""" overload [] operator - set() method """
i0, i1 = self._parsekey(key)
self.dd[i0][i1] = value
Update: Expanded answer to allow something like AA["word1", "word3"] = 23
. 更新:扩展答案以允许类似
AA["word1", "word3"] = 23
。
Maybe you can try initializing your table with 也许您可以尝试使用初始化表
self.table = {r : { c : 0 for c in ['word1', 'word2']} for r in ['word3', 'word4']}
and then you can access each position by 然后您可以通过以下方式访问每个职位
self.table['word3']['word1'] = 2
Python doesn't have a ready-made instruction to create a bi-dimensional matrix, but it's easy to do that using list comprehensions: Python没有创建二维矩阵的现成指令,但是使用列表推导很容易做到这一点:
matrix = [[0] * cols for i in range(rows)]
then you can access the matrix with, for example 然后您可以使用
matrix[row][col] += 42
assuming rows=10
and cols=20
then the row
index must go from 0 to 9 and the col
index from 0 to 19. You can also use negative indexes to mean counting from the end; 假设
rows=10
, cols=20
则row
索引必须从0到9, col
索引必须从0到19。 for example 例如
matrix[-1][-1] = 99
will set the last cell to 99 将最后一个单元格设置为99
If you are not opposed to using an external library, you might check out 如果您不反对使用外部库,则可以签出
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.