ns533
ns533

Reputation: 311

Python: Filter list full of unicode and lists to just strings

Say I have a list of lists like the following.

lst = [[u'1'], [[], [u'Qjfe dw Dvrferk (bfw)'], []], [u'86,865,281'], [u'$22.34'], [u'-0.31'], [u'-1.37']]

What would be the best approach (preferably using lambda) to turn it into a list of strings like this.

lst = ['1', 'Qjfe dw Dvrferk (bfw)', '86,865,281', '$22.34', '-0.31', '-1.37'] 

Upvotes: 1

Views: 106

Answers (1)

Dan D.
Dan D.

Reputation: 74645

Looks like a deep flatten to me.

def deep_flatten(L):
    for e in L:
        if isinstance(e, list):
           for e in deep_flatten(e):
               yield e
        else:
            yield e

lst = [[u'1'], [[], [u'Qjfe dw Dvrferk (bfw)'], []], [u'86,865,281'], [u'$22.34'], [u'-0.31'], [u'-1.37']]

list(deep_flatten(lst))

results in:

[u'1', u'Qjfe dw Dvrferk (bfw)', u'86,865,281', u'$22.34', u'-0.31', u'-1.37']

Upvotes: 4

Related Questions