Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split words in a nested list into letters

Tags:

python

I was wondering how I can split words in a nested list into their individual letters such that

[['ANTT'], ['XSOB']]

becomes

[['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']]
like image 939
Markus Avatar asked Oct 31 '12 09:10

Markus


2 Answers

Use a list comprehension:

[list(l[0]) for l in mylist]

Your input list simply contains nested lists with 1 element each, so we need to use l[0] on each element. list() on a string creates a list of the individual characters:

>>> mylist = [['ANTT'], ['XSOB']]
>>> [list(l[0]) for l in mylist]
[['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']]

If you ever fix your code to produce a straight up list of strings (so without the single-element nested lists), you only need to remove the [0]:

>>> mylist = ['ANTT', 'XSOB']
>>> [list(l) for l in mylist]
[['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']]
like image 82
Martijn Pieters Avatar answered Oct 22 '22 10:10

Martijn Pieters


You could you a functional approach (still I would prefer list comprehensions as in Martijn Pieters' answer):

>>> from operator import itemgetter
>>> delisted = map(itemgetter(0),[['ANTT'],['XSOB']])  # -> ['ANTT', 'XSOB']
>>> splited = map(list,delisted)  # -> [['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']]

Or, as a oneliner:

>>> map(list,map(itemgetter(0),[['ANTT'],['XSOB']]))
[['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']]
like image 2
ovgolovin Avatar answered Oct 22 '22 09:10

ovgolovin