0

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]]

2 Answers 2

1

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]]
Sign up to request clarification or add additional context in comments.

1 Comment

That's great, thank you, yes i was struggling with the logic of that extra for loop. Really helpful, thank you.
0

It's not that hard actually:

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

easier way but longer:

s = s.split('/n')
new = []
for i in s:
    new.append(i.split())
print(new)

output:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.