Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a multi line string into a matrix in python

I have this design, for example:

design = """xxx
yxx
xyx"""

And I would like to convert it to an array, a matrix, nested lists, like this:

[['x', 'x', 'x'], ['y', 'x', 'x'], ['x', 'y', 'x']]

How would you do this, please?

like image 670
mightyiam Avatar asked Jan 19 '26 05:01

mightyiam


1 Answers

Use str.splitlines with either map or a list comprehension:

Using map:

>>> map(list, design.splitlines())
[['x', 'x', 'x'], ['y', 'x', 'x'], ['x', 'y', 'x']]

List Comprehension:

>>> [list(x) for x in  design.splitlines()]
[['x', 'x', 'x'], ['y', 'x', 'x'], ['x', 'y', 'x']]
like image 92
Ashwini Chaudhary Avatar answered Jan 20 '26 20:01

Ashwini Chaudhary