Domanda

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?

È stato utile?

Soluzione

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']]
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top