Work 2D python arrays

0

Work 2d lists (I think you know how arrays).

How is it done to fill them out? I know it's basic but I do not understand it.

I know that if I have

lista1 = []
for x in xrange (0,5):
    lista1.append(x)
print lista1

I fill in my list so that it looks like: [0,1,2,4]

But in my case I would like to do "two columns" (really in one I want to put letters and in other numbers) How do I assign the value that I want to the first column and the value that I want to the second column? ? Use .append() and I get an error and if I assign it with an equal sign too.

lista2 = [[],[]]

lista2[[0][0]].append('a')
lista2[[0][1]].append(1)
print lista2

Health and thanks!

    
asked by NEA 24.10.2018 в 19:35
source

2 answers

0

In python, a matrix can be represented as a list of lists, for example, we have the matriz = [[],[],[]] , it contains three lists, these lists indicate the rows in the matrix, and the values contained within each of these lists would indicate a column in the matrix, for this list of lists, matriz = [[1,2,3],['a','b','c'],[5,6,7]] the matrix would look like this: 1 2 3 a b c 5 6 7 the first row would be the first list, the second row would be the second list and so on, for the columns the same, the first column would be all the elements in the first position of all the lists, the second column all the elements of the second position in all the lists and so on, to create a square matrix, the number of items in the lists must be equal, and therefore equal to the size of the containing list, in this case matriz a more practical example: matriz = [] for fila in range(4): fila_nueva=[] for columna in range(4): fila_nueva.append(str("celda"+str(fila+1,columna+1)))) matriz.append(fila_nueva) with this should be something like this celda 1,1 celda 1,2 celda 1,3 celda 1,4 celda 2,1 celda 2,2 celda 2,3 celda 2,4 celda 3,1 celda 3,2 celda 3,3 celda 3,4 celda 4,4 celda 4,2 celda 4,3 celda 4,4 so to access an element you must first call in which row to search and then in which posisicon of that list, for example to remove the element that is in cell 3, 3, would be elemento = matriz[2][2]

    
answered by 24.10.2018 в 19:59
0

To create a matrix, what is done is a list of lists, for example:

matriz = [
    [" ", 1, 2, 3, 4], # Fila 0
    ["A", 1, 2, 3, 4], # Fila 1
    ["B", 1, 2, 3, 4], # Fila 2
    ["C", 1, 2, 3, 4], # Fila 3
    ["D", 1, 2, 3, 4]  # fila 4
    # Columnas
]

To access row 1 and column 3

fila = 1
columna = 3
print(matriz[fila][columna]

To assign a new value to a row and column

matriz[fila][columna] = "N"
# Para una mejor visualización usa pretty print
from pprint import pprint
pprint(matriz)

Add a new element to row 2

fila = 2
matriz[fila].append("NuevoElemento")
from pprint import pprint
pprint(matriz)
    
answered by 24.10.2018 в 19:55