How can i make a 2D array with existing lists?

2020-05-06 11:42发布

for instance, i have a txt data called 'mazeline' like this:

abcd
cdae
korp

So i first made 3 lists:

mazeline = readmaze.split()
mline0 =  list(mazeline[0])
mline1 =  list(mazeline[1])
mline2 =  list(mazeline[2])

So the 3 lists are:

mline0 = [a,b,c,d]
mline1 = [c,d,a,e]
mline2 = [k,o,r,p]

and i want to make a 2D array like this:

[[a,b,c,d],[c,d,a,e],[k,o,r,p]]

or is there any way that i can make a 2d array directly from the first data?

any suggestions? any help would be good.

2条回答
兄弟一词,经得起流年.
2楼-- · 2020-05-06 12:22

Just put the lists inside another list

res = [mline0, mline1, mline2]

more simply, you can skip the intermediate variables and use a list comprehension

res = [list(mline) for mline in readmaze.split()]
查看更多
爷的心禁止访问
3楼-- · 2020-05-06 12:25

Try this list comprehension:

[[int(i) for i in line.strip()] for line in open('file/path')]
查看更多
登录 后发表回答