Python: Return a list in 2D format

Asked

Viewed 81 times

0

I want to use the __str__ to receive a list and returns it in the form of a matrix.

Example:

list_exemplo = [[0,1], [2,3]]would return as:

[[0, 1],
[2, 3]]

How do I do it in the method __str__?

  • 1

    Could you elaborate further? Are you implementing some class to use the __str__?

2 answers

2

as Anderson has already pointed out in the comments, you should implement the function __str__, however what gives a intender in your duvia is that you want a feedback when creating the list, that you should already implement the constructor __init__

class Lista(list):
    def __init__(self, *args):
        super().__init__(*args)
        print(self.__str__())

    def __str__(self):
        return super().__str__().replace('],', ']\n')

a = Lista([[1,2],[3,4]])

this example ñ is final, I believe there are better ways to do this

2

If you just want to format a list of lists in matrix form, you don’t need to create a class for that - and then you don’t need a method __str__ - a function that receives its data structure is sufficient.

Now, implementing a class has other advantages: it allows you to actually treat your structure as a matrix, and even implement operations as they are defined for matrices. But let’s not get ahead of ourselves.

For print formatting, a fundamental method of understanding is the .join strings - it allows strings that are part of a list to be pasted into a single string, using the part that calls the .join as an element of glue between them. In this case, the desired "glue" element is a line change - for this we use only special character \n (line feed). If you want to display the starting brackets and a comma at the end of each line, so that the output is valid Python, you can do:

def formata_matriz(matriz):
    return "[{}]".format(",\n".join(str(linha) for linha in matriz))

(Remember that you have to use a print(...) on the result of it in order for n to be expanded to a line change:

In [617]: print(formata_matriz([[1,2],[3, 4]]))                                                                                                      
[[1, 2],
[3, 4]]

If you want something more "matrix-like" you can leave out the brackets, the commas at the end, use formatting and tabulation characters, and the character | to delimit the matrix:

def formata_matriz(matriz):
    return "\n".join("|{}|".format(", ".join(
        f"{elemento:>5.2f}" for elemento in linha)) for linha in matriz)

In this case I use a f-string, I use the mini-formatting language .format after the : to ensure right alignment for numbers, with space for 5 digits, being two after the . decimal:

In [630]: print(formata_matriz([[1.45,2.3],[23, 4.0]]))                                                           
| 1.45,  2.30|
|23.00,  4.00|

Browser other questions tagged

You are not signed in. Login or sign up in order to post.