2013-10-28 68 views
1

我有这样的设计,例如:如何将多行字符串转换成矩阵蟒蛇

design = """xxx 
yxx 
xyx""" 

而且我想将它转化成一个阵列,矩阵,嵌套列表,就像这样:

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

请问您会怎么做?

+1

如果你真的希望它像一个数组,而不是列表列表(很难索引列),那么你应该把它放入一个Numpy'array'中。 – beroe

+0

是x和y的意思是变量名称还是1个字母的字符串? – Back2Basics

回答

8

使用str.splitlines有两种maplist comprehension

使用map

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

列表综合:

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