Split words in a nested list into letters

I was wondering how I can break the words in a nested list into separate letters so that

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

becomes

 [['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']] 
+5
source share
4 answers

Use list comprehension:

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

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

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

If you ever corrected your code to get a direct list of strings (without nested lists with one element), you only need to delete [0] :

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

You could use a functional approach (as before, I would prefer an understanding of lists, as in Martin Peter's 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 oneliner:

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

All answers given so far include - somewhat suspicious - 0 literal. At first glance, it seems that this is a somewhat artificial addition, since the original problem does not contain integer literals.

But the input has - of course - some special properties , except that it is just a list. This is a list of lists with exactly one string literal. In other words, a package of individually wrapped objects (strings). If we rephrase the original question and the accepted answer , we can make the connection 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 
0
source

Source: https://habr.com/ru/post/1443189/


All Articles