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

对着背影说爱祢 提交于 2019-12-02 23:35:51

问题


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.


回答1:


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()]



回答2:


Try this list comprehension:

[[int(i) for i in line.strip()] for line in open('file/path')]


来源:https://stackoverflow.com/questions/12768862/how-can-i-make-a-2d-array-with-existing-lists

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!