Define array in python

2

I need to create an array and populate it with random values ( randint(0,9) ), except for the same rows and columns. For example, this way:

   A| B| C| D| E
A  x| 2| 1| 4| 2 
B  1| x| 1| 1| 2
C  5| 1| x| 4| 3
D  8| 2| 1| x| 2
E  5| 4| 1| 4| x

I've already done this:

from random import randint


def matrix():

    n=5 
    m=10

    matrixC = []
    value = (randint(0,9))

    #adicionar esse valores à matriz gerada
    for i in range(0, n):
        for j in range(0, n):
            if i != j:
                matrizC.append[[random.random() for i in range(n)] for j in range(n)]
            else:
                matrizC.append("x")

[UPDATE]

Following the directions I have this:

from random import randint

def matriz():
    #pedir o n
    n=5
    matriz = []  #declaração da matriz

    n_col=1
    n_lin=1

    for n_lin in range(n):
        linha = [] # cria uma linha para a matriz
        for n_col in range(n):
            if n_lin==n_col:
                linha.append('x')               
            else:
                linha.append(randint(1,9))

    matriz.append(linha)

    n_col=1
    n_lin=1 

    for n_lin in range(n):
        for n_col in range(n):
            print(matriz[n_lin][n_col], end='\t')

In the 3rd for the impression of the matrix, but when compiling I do not get any results.

    
asked by anonymous 19.11.2018 / 15:36

1 answer

1

The problem is that you are mixing two techniques. One way to do this is to use% s of structured% s on each line:

matriz = []
for n_lin in range(5):
    linha = [] # cria uma linha para a matriz
    for n_col in range(5):
        if n_lin == n_col:
            linha.append('x')
        else:
            linha.append(randint(0, 9))
    matriz.append(linha)

The other way is to put it all on one line, the famous "list understanding":

matriz = [['x' if x == y else randint(0, 9) for x in range(5)] for y in range(5)]
    
19.11.2018 / 20:53