2016-11-27 53 views
-2
Sum Qo'D tob 'e' SoH 
jeD ngeH maHaD 'e roj message maHa might consider 
leaving SoH yong roj 'baD yInD SoHDa Haup lives 
jeD ngeH maHaD 'e roj message maHa might consider 

我如何可以將其轉換到這個列表:Python3創建列表

[['Sum', 'Qo'D', 'tob', "'e'", 'SoH'], 
['jeD', 'ngeH', 'maHaD', "'e", 'roj', 'maHa', 'might'], 
['leaving', 'SoH', 'yong', 'roj', "'baD", 'yInD', 'SoHDa', 'Haup'] 
['jeD', 'ngeH', 'maHaD', "'e", 'roj', 'message', 'maHa', 'might', 'consider']] 

例如list[0]['Sum', 'Qo'D', 'tob', "'e'", 'SoH']list[0][0]Sum

+0

見:['str.split()'](HTTPS://docs.python .ORG/3 /庫/ stdtypes.html#str.split)。 –

回答

1

如果:

text="""Sum Qo'D tob 'e' SoH 
jeD ngeH maHaD 'e roj message maHa might consider 
leaving SoH yong roj 'baD yInD SoHDa Haup lives 
jeD ngeH maHaD 'e roj message maHa might consider""" 

做與oneliner(使用listcomp):

print([line.split() for line in text.splitlines()]) 

結果:

[['Sum', "Qo'D", 'tob', "'e'", 'SoH'], 
['jeD', 'ngeH', 'maHaD', "'e", 'roj', 'message', 'maHa', 'might', 'consider'], 
['leaving', 'SoH', 'yong', 'roj', "'baD", 'yInD', 'SoHDa', 'Haup', 'lives'], 
['jeD', 'ngeH', 'maHaD', "'e", 'roj', 'message', 'maHa', 'might', 'consider']] 

編輯:吉姆建議使用map替代,這這裏有道理,因爲我們不需要lambda來提供給map(我們已經可以使用str.split):

list(map(str.split, text.splitlines())) 

list是必需的因爲蟒3 map返回迭代)

+0

或者:'list(map(str.split,text.split('\ n')))'。 –

+0

是的。自從python 3開始,我就忘了map(有意),因爲如果它是你的最終輸出,你必須創建一個列表。我注意到'map','filter'的使用真的很少,因爲使用了listcomps。我用'map'在這裏發佈的所有解決方案都沒有得到提升,與listcomps併發的解決方案做... –

+0

哈哈,我仍然覺得地圖視覺吸引力,無論哪種方式,呈現兩個是我總是嘗試和做的:-) –