2d array of lists in python

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

    Just as you wrote it:

    >>> matrix = [["str1", "str2"], ["str3"], ["str4", "str5"]]
    >>> matrix
    [['str1', 'str2'], ['str3'], ['str4', 'str5']]
    >>> matrix[0][1]
    'str2'
    >>> matrix[0][1] += "someText"
    >>> matrix
    [['str1', 'str2someText'], ['str3'], ['str4', 'str5']]
    >>> matrix[0].extend(["str6"])
    >>> matrix[0]
    ['str1', 'str2someText', 'str6']
    

    Just think about 2D matrix as list of the lists. Other operations also work fine, for example,

    >>> matrix[0].append('value')
    >>> matrix[0]
    [0, 0, 0, 0, 0, 'value']
    >>> matrix[0].pop()
    'value'
    >>> 
    

提交回复
热议问题