Python3创建列表

时间:2016-11-27 15:40:33

标签: python python-3.x

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

如何将其转换为此列表:

[['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

1 个答案:

答案 0 :(得分: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']]

编辑:Jim使用map提出了另一种选择,这在我们这里是有道理的,因为我们不需要lambda来提供map(我们已经可以使用{{1} }}):

str.split

list(map(str.split, text.splitlines())) 是必需的,因为python 3 list返回迭代器)