2

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?

2
  • 1
    If you really want it to act like an array, rather than a list of lists (hard to index columns) then you should put it into a Numpy array. Commented Oct 28, 2013 at 18:48
  • are the x's and y's meant to be variable names or 1 letter strings? Commented Oct 28, 2013 at 21:07

1 Answer 1

9

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

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.