2d array of lists in python

前端 未结 6 1348
北海茫月
北海茫月 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:39

    You can either do it with the basic:

    matrix = [
       [["s1","s2"], ["s3"]],
       [["s4"], ["s5"]]
    ]
    

    or you can do it very genericially

    from collections import defaultdict
    m = defaultdict(lambda  : defaultdict(list))
    m[0][0].append('s1')
    

    In the defaultdict case you have a arbitrary matrix that you can use, any size and all the elements are arrays, to be manipulated accordingly.

提交回复
热议问题