Python中列表的嵌套列表

时间:2015-08-27 16:22:47

标签: python list

我有以下列表:

mylst = ['bla,bli', 'blula', 'blabla,bloblu,blibla', 'bla']

如何将其转换为嵌套列表,例如:

mylst = [['bla','bli'], ['blula'], ['blabla','bloblu','blibla'], ['bla']]

3 个答案:

答案 0 :(得分:3)

如果您想要用逗号分隔,只需在list comprehension中执行此操作:

mylst = [elem.split(',') for elem in mylst]

str.split() method生成新列表:

>>> mylst = ['bla,bli', 'blula', 'blabla,bloblu,blibla', 'bla']
>>> [elem.split(',') for elem in mylst]
[['bla', 'bli'], ['blula'], ['blabla', 'bloblu', 'blibla'], ['bla']]

答案 1 :(得分:3)

>>> mylst = ['bla,bli', 'blula', 'blabla,bloblu,blibla', 'bla']
>>> mylst = [item.split(',') for item in mylst]
>>> mylst
[['bla', 'bli'], ['blula'], ['blabla', 'bloblu', 'blibla'], ['bla']]

答案 2 :(得分:1)

实际上真的很简单!

myLst2 = map(lambda x: x.split(','), mylst)

正如Martijn Pieters在python3中所指出的,这将返回一个map迭代器。要获得列表,请执行以下操作:

mapIter = map(lambda x: x.split(','), mylst)
myLst2 = list(mapIter)