如何在python中将多行字符串转换为矩阵

mig*_*iam 1 python list converter matrix multiline

我有这个设计,例如:

design = """xxx
yxx
xyx"""
Run Code Online (Sandbox Code Playgroud)

我想将它转换为数组,矩阵,嵌套列表,如下所示:

[['x', 'x', 'x'], ['y', 'x', 'x'], ['x', 'y', 'x']]
Run Code Online (Sandbox Code Playgroud)

请问你会怎么做?

Ash*_*ary 8

使用str.splitlines任何一个map或一个list comprehension:

使用map:

>>> map(list, design.splitlines())
[['x', 'x', 'x'], ['y', 'x', 'x'], ['x', 'y', 'x']]
Run Code Online (Sandbox Code Playgroud)

列表理解:

>>> [list(x) for x in  design.splitlines()]
[['x', 'x', 'x'], ['y', 'x', 'x'], ['x', 'y', 'x']]
Run Code Online (Sandbox Code Playgroud)