Sunday 15 February 2015

How to split a list on the basis of an element in the list in python? -



How to split a list on the basis of an element in the list in python? -

i have list of strings this: [['root', 's'], ['s', 'np', ')', 'vp', ')'], ['np', 'dt', 'nn']].

i want whenever ')' encountered in list, should split internal list, , instead of ')', add together ' ' both new lists formed. in above example, there 2 occurrences of ')', want output this:

[['root', 's'], ['s', 'np', ' '], [' ', 'vp', ' '], [' '], ['np', 'dt', 'nn']]

how this?

convert list string. create replacements like. utilize ast bundle convert string data structure (list in case) if string in proper format. demo:

>>> import ast >>> lst=[['root', 's'], ['s', 'np', ')', 'vp', ')'], ['np', 'dt', 'nn']] >>> lst=str(lst) >>> lst=lst.replace('\')\'','\' \'], [\' \'') >>> lst=ast.literal_eval(lst) >>> lst [['root', 's'], ['s', 'np', ' '], [' ', 'vp', ' '], [' '], ['np', 'dt', 'nn']]

python

No comments:

Post a Comment