2d array of lists in python

前端 未结 6 1349
北海茫月
北海茫月 2021-01-12 07:05

I am trying to create a 2d matrix so that each cell contains a list of strings. Matrix dimensions are known before the creation and I need to have access to any element from

6条回答
  •  佛祖请我去吃肉
    2021-01-12 07:51

    One option is to write your own class, where you overload the [] operator. Take a look for that in here: http://www.penzilla.net/tutorials/python/classes/ . Acessing a 2d elment in 1d is y * rowSize + x. Extending the elements by writing an append function, which would use append rowSize times.

    If you want to create a 2d matrix and you need to preallocate than, you could do the following:

    x,y = 3,3
    A = [ [None]*x for i in range(y) ]
    

    You can replace None with the value you want. And you can use .extend to add additional values.

提交回复
热议问题