Flatten a list of strings and lists of strings and lists in Python -
this question has answer here:
similar questions have been asked before, solutions don't work use case (e.g., making flat list out of list of lists in python , flattening shallow list in python. have list of strings , lists, embedded list can contain strings , lists. want turn simple list of strings without splitting strings list of characters.
import itertools list_of_menuitems = ['image10', ['image00', 'image01'], ['image02', ['image03', 'image04']]] chain = itertools.chain(*list_of_menuitems)
resulting list:
['i', 'm', 'a', 'g', 'e', '1', '0', 'image00', 'image01', 'image02', ['image03', 'image04']]
expected result:
['image10', 'image00', 'image01', 'image02', 'image03', 'image04']
what's best (pythonic) way this?
the oft-repeated flatten
function can applied circumstance simple modification.
from collections import iterable def flatten(coll): in coll: if isinstance(i, iterable) , not isinstance(i, basestring): subc in flatten(i): yield subc else: yield
basestring
make sure both str
, unicode
objects not split.
there versions count on i
not having __iter__
attribute. don't know that, because think str
has attribute. but, it's worth mentioning.
(please upvote linked answer.)
Comments
Post a Comment