Search code examples
pythonoopmethodspython-class

Convert string with hard coded line breaks into matrix in python


I am trying to create a class that takes a string of digits with hard coded line breaks and outputs a matrix and details about that matrix. In the first instance i just want to be able to create the matrix but I am struggling. I'm aware that I could probably do this very easily with numpy or something similar but trying to practice.

class Matrix:
def __init__(self, matrix_string):
    self.convert_to_list = [int(s) for s in str.split(matrix_string) if s.isdigit()]
    self.split = matrix_string.splitlines()

I think i want to combine the two things I have already done but I cant figure out how to apply my convert_to_list method to every element in my split method.

Getting very confused.

SAMPLE INPUT/OUTPUT

Input = " 1 8 7 /n 6 18 2 /n 1 9 7 "

Desired Output = [[1, 8, 7], [6, 18, 2], [1, 9, 7]]

Solution

  • It looks like you want a list of lists. For that you can use nested list comprehension.

    s = " 1 8 7 /n 6 18 2 /n 1 9 7 "
    lst = [[int(x) for x in r.split()] for r in s.split('/n')]
    print(lst)
    

    Output

    [[1, 8, 7], [6, 18, 2], [1, 9, 7]]