2014-04-04 80 views
0

我走在一個文件的字符數行,像這樣:有沒有更有效的方法來創建這個2D列表?

oeoeoeo 
eoeoeoe 
oeoeoeo 
eoeoeoe 
oeoeoeo 

我希望把它們放入一個二維列表,像這樣:

[['o', 'e', 'o', 'e', 'o', 'e', 'o'], 
['e', 'o', 'e', 'o', 'e', 'o', 'e'], 
['o', 'e', 'o', 'e', 'o', 'e', 'o'], 
['e', 'o', 'e', 'o', 'e', 'o', 'e'], 
['o', 'e', 'o', 'e', 'o', 'e', 'o']] 

這是我的」 m目前正在完成此操作:

map2dArray = [] 

for line in input_file: 
    lineArray = [] 
    for character in line: 
     lineArray.append(character) 
    map2dArray.append(lineArray) 

在Python中有更好的方法來做到這一點嗎?

回答

4

是,在單行:

map(list, input_file) 

或在Python 3:

list(map(list, input_file)) 

這通常留下的結果,換行,所以如果你想擺脫那些:

[list(line.strip('\n')) for line in input_file] 
相關問題