Markus
Markus

Reputation: 121

Split words in a nested list into letters

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']]

Upvotes: 5

Views: 1077

Answers (4)

Wolf
Wolf

Reputation: 10238

All answers given so far include a - somewhat suspicious - 0 literal. At first glance this seem to be a somewhat artificial additive, since the original task doesn't include any integer literal.

But the input has - of course - some special properties besides being just a list. It's a list of lists with exactly one string literal in it. In other words, a package of individually boxed objects (strings). If we rephrase the original question and the accepted answer, we can make the relation between [x] and [0] more obvious:

package = [['ANTT'], ['XSOB']]
result = [list(box[0]) for box in package]   # 0 indicates first (and only) element in the box

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1122252

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']]

Upvotes: 10

ovgolovin
ovgolovin

Reputation: 13410

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']]

Upvotes: 2

Oleksii Kachaiev
Oleksii Kachaiev

Reputation: 6234

>>> map(lambda s: map(list, s)[0], [['ANTT'],['XSOB']])
[['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']]

Upvotes: 1

Related Questions