[Solved] Create matrix out of two lists while populating body of matrix using custom method in Python [closed]


We have:

xs = ["A", "B", "C"]
ys = [1, 2, 3]

Let’s take a simple example: f repeats y times the char x

f=lambda x,y:x*y

The computation of the matrix is obvious: for each y, we compute a row of f(x,y) with all x in xs.

matrix = [[f(x,y) for x in xs] for y in ys]
print ("matrix", matrix)

The display of the matrix is more interesting. First, we need to compute the width of each column.
The width of a column is the width of its widest element. If col is the column, the width is max(len(str(z)) for z in col).
The first column is the ys. To get the columns of the matrix, we just zip every row: zip(*matrix) is the same as zip(row[0], row[1], ...)

ws = [max(len(str(y)) for y in ys)] + [max(len(str(y)) for y in col) for col in zip(*matrix)]
print ("ws", ws)

Now, we can print the matrix. The first row is [" "]+xs, the following rows are [y]+row where y is the label of the row. We get the labels and the rows with a new zip: zip(ys, matrix).
We have our rows, and we zip the values with the width of the columns (another zip! zip(zs, ws)) to adjust (ljust) the columns. The tab separates the columns:

for zs in ([" "]+xs, *[[y]+row for y, row in zip(ys, matrix)]): 
    print ("\t".join([str(z).ljust(w) for z,w in zip(zs, ws)]))

Output:

    A   B   C  
1   A   B   C  
2   AA  BB  CC 
3   AAA BBB CCC

Try it online!

1

solved Create matrix out of two lists while populating body of matrix using custom method in Python [closed]