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']]
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']]
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']]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With