replace items in nested lists in python

3

I want to replace items in lists of lists to draw a cross. So for example the list:

x="X"
lista =[[x," "," "," ",x],[" ",x," ",x, " "],[" "," ",x," "," "],[" ",x," 
",x, " "],[x," "," "," ",x]]
for l in lista:
        print (" ".join(l))

results in:

X       X
  X   X  
    X    
  X   X  
X       X

But I can not successfully replace the items in an order list " size ", as shown in the following code:

size =int(input("Which is the size of the nested lists? "))
col=[]
for x in range (size):
    col .append(str(x))
tablero =[]
for b in range(size):
    tablero.append(col)

for row in range(len(tablero)):
    for col in range(len(tablero)):
        if col == row:
            tablero[col][row]= "X"     
for l in tablero:
    print (" ".join(l))
    
asked by Hermes Morales 06.08.2018 в 06:30
source

2 answers

1

In your case you could try something like this to avoid those nested cycles:

size =int(input("Which is the size of the nested lists? "))

tablero = []
for i in range(size):
    row = [" "] * size // crea una lista de tamaño size
    row[i] = "X" // agrega "X" en la posición i 
    row[size - i - 1] = "X" // agrega "X" en la posición (size - i - 1)
    tablero.append(row)

The idea is to create the empty board first and then add the rows. In each row you select the position you want to edit.

    
answered by 06.08.2018 / 08:02
source
1

Hello my solution is this:

n = 10

# matrix de n*n
m = [ [' ' for y in range(n)] for x in range(n)]

for i,r in enumerate(m):
    m[i][i] = 'x'
    m[i][n-i-1] = 'x'
for r in m:
    print(''.join(r))
    
answered by 06.08.2018 в 08:06