简体   繁体   中英

Create python 2d array indexed by string

(I'm not too great at python, so forgive me if this is a stupid question)

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).

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 .

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:

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; for example

matrix[-1][-1] = 99

will set the last cell to 99

If you are not opposed to using an external library, you might check out

Pandas Data Frames

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM