i have list in python how can i generate a matrix by subtracting the list element by each othe and create a comaprision matrix and save it into csv
list_a = [1,2,4]
list_b = [1,2,4]
for i in list_a:
for j in list_b:
print(i - j)
i want to write its output like matrix [0 1 3 ]
[-1 0 2 ]
[-3 -2 0 ]
CodePudding user response:
you can transpose the list of list using map and zip
list_a = [1,2,4]
list_b = [1,2,4]
matrix_output = []
for i in list_a:
matrix_output.append([])
for j in list_b:
matrix_output[-1].append(i-j)
matrix_output_transposed = list(map(list, zip(*matrix_output)))
for cell in matrix_output_transposed:
print(cell)
CodePudding user response:
if u use numpy, then it is most easiest solution. following snip generates expected results. please check once
import numpy as np
list_a = [1,2,4]
list_b = [1,2,4]
y = np.subtract.outer(np.array(list_a), np.array(list_b)).T
print(y)