2d array of lists in python

I am trying to create a 2d matrix so that each cell contains a list of rows. Matrix sizes are known before creation, and I need to have access to any element from the very beginning (without dynamically filling the matrix). => I think some preliminary distribution of space is required.

For example, I would like to have a 2X2 matrix:

[['A','B']          ['C'];
  ['d']       ['e','f','f']]

with support for traditional matrix access operations, for example

(Matrix[2][2]).extend('d')

or

tmp = Matrix[2][2]
tmp.extend('d')
Matrix[2][2] = tmp

to manage the contents of the cells.

How to do this in python?

+7
source share
5 answers

Just as you wrote this:

>>> 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 of the 2D matrix as a list of lists. Other operations also work fine, for example,

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

:

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

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

defaultdict , , , .

+4

, , , 3- , "" , kth jth ith matrix[i][j][k].

, 2X2 , , :

def alloc_matrix2d(W, H):
    """ Pre-allocate a 2D matrix of empty lists. """
    return [ [ [] for i in range(W) ] for j in range(H) ]

, , , , 2X2 :

[
    [
        ['A','B'], ['C']
    ],
    [
        ['d'], ['e','f','f']
    ]
]

" " :

(Matrix[2][2]).extend('d')

, prealocated 2X2, . Python , : [0][0], [0][1], [1][0] [1][1] ( , Python). Matrix[2][2] - third , , 2X2.

, - , ( ):

Matrix[1][1].extend('d')

IndexError , 2X2 :

[
    [
        ['A', 'B'], ['C']
    ],
    [
        ['d'], ['e', 'f', 'f', 'd']
    ]
]

, , , 2D- ( lists):

def repr_matrix2d(name, matrix):
    lines = ['{} = ['.format(name)]
    rows = []
    for row in range(len(matrix)):
        itemreprs = [repr(matrix[row][col]) for col in range(len(matrix[row]))]
        rows.append('\n    [\n        {}\n    ]'.format(', '.join(itemreprs)))
    lines.append('{}\n]'.format(','.join(rows)))

    return ''.join(lines)

, .

+3

- , []. : http://www.penzilla.net/tutorials/python/classes/. 2d 1d y * rowSize + x. append, append rowSize.

2d-, , :

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

None . .extend .

+1

, , , , 2d python3.4 ,

list=[]
list1=[]
list2=[]
list3=[]
answer1='yes'
answer2='yes'
answer3='yes'

while answer1=='yes':
    item1=input("Please input a list element for your first list:")
    answer1=input("Do you want to continue:")
    list1.append(item1)

while answer2=='yes':
    item2=input("Please input a list element for your second list:")
    answer2=input("Do you want to continue:")
    list2.append(item2)

while answer3=='yes':
    item3=input("Please input a list element for your third list:")
    answer3=input("Do you want to continue:")
    list3.append(item3)

list.append(list1)
list.append(list2)
list.append(list3)

print(list)
0

All Articles