-1

i'd like create in python a matrix with all zeros except for some value selected from a list. For example (very stupid) from

l=[0,1,2,3]

i'd like create a matrix (a list of list) with the letter "x" in position l[0] l[1] etc.. like this:

  [x, 0, 0, 0]    
  [0, x, 0, 0]    
  [0, 0, x, 0]
  [0, 0, 0, x]

i'd like make it interactive, with a variable length (not always 4) maybe giving on input

cs95
  • 379,657
  • 97
  • 704
  • 746
farso92
  • 41
  • 5

2 Answers2

1

You should use numpy's diag function.

import numpy as np
np.diag(l)

array([[0, 0, 0, 0],
       [0, 1, 0, 0],
       [0, 0, 2, 0],
       [0, 0, 0, 3]])

With pure python, initialise an empty 2D list and populate the diagonal after.

diag = [[0] * len(l) for _ in range(len(l))]
for i, e in enumerate(l):
    diag[i][i] = e

diag
# [[0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 2, 0], [0, 0, 0, 3]]
cs95
  • 379,657
  • 97
  • 704
  • 746
0

If I understood you correctly, you want non-zero values to be placed based on the list. So, maybe something like this:

val = 'x'
l = [2,1,0,3]
matrix = [[val if i == e else 0 for i in range(len(l))] for e in l]
print(matrix)

Output will be like this:

[[0, 0, 'x', 0], [0, 'x', 0, 0], ['x', 0, 0, 0], [0, 0, 0, 'x']]