开发者

Split the string 'abcde' into a list with separate elements

I have a string like 'g fmnc wms bgblr rpylqjyrc gr zw fylb'. I use the .split() function in python and get ['g', 'fmnc', 'wms', 'bgblr', 'rpylqjyrc', 'gr', 'zw', 'fylb']

Now I want to split each of the elements into seperated lists like: [['g'], [['f'],['m'],['n'],['c']],...] and so on.

My problem i开发者_开发技巧s to split the element ['abcbd'] into [['a'],['b'],['c'],['b'],['d']]


Try this:

[list(item) for item in s.split()]

It will give you this [['g'], ['f', 'm', 'n', 'c'], ...] which isn't quite what you asked for, but probably what you meant.


>>> sample = 'g fmnc wms bgblr rpylqjyrc gr zw fylb'
>>> [ list(x) for x in sample.split() ]
[['g'], ['f', 'm', 'n', 'c'], ['w', 'm', 's'], ['b', 'g', 'b', 'l', 'r'], ['r', 'p', 'y', 'l', 'q', 'j', 'y', 'r', 'c'], ['g', 'r'], ['z', 'w'], ['f', 'y', 'l', 'b']]


a='g fmnc wms bgblr rpylqjyrc gr zw fylb'
ml = lambda x: len(x) == 1 and [x] or map(ml, x)
print ml(a.split())

[['g'], [['f'], ['m'], ['n'], ['c']], [['w'], ['m'], ['s']], [['b'], ['g'], ['b'], ['l'], ['r']], [['r'], ['p'], ['y'], ['l'], ['q'], ['j'], ['y'], ['r'], ['c']], [['g'], ['r']], [['z'], ['w']], [['f'], ['y'], ['l'], ['b']]]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜