Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flattening nested list

Tags:

python

list

I have hundreds of rows of data that look like this:

[[u' 16 '], [u'1x23'], [u'Mr Test', u' (5)'], [u'John Smith'], [u'54.5'], [], [u'10%'], [u'40%'], [u'$26,503']]

Some of the values are nested and some also are empty.

I'm trying to massage it to be like this:

['16', '1x23', 'Mr Test', '(5)', 'John Smith', '54.5', '', '10%', '40%', '$26,503']

I've tried some ideas found on here like flattening, including the following routine:

def traverse(o, tree_types=(list, tuple)):
    if isinstance(o, tree_types):
        for value in o:
            for subvalue in traverse(value):
                yield subvalue
    else:
        yield o

This worked for some tables I've already parsed but only when there are no empty values.

like image 655
croc Avatar asked Feb 28 '26 20:02

croc


2 Answers

Try this,

sum((item or [""] for item in a), [])

Weird huh?

like image 172
Jakob Bowyer Avatar answered Mar 02 '26 09:03

Jakob Bowyer


This will do the trick (even with empty values):

import operator
def flatten(a):
    return reduce(operator.add, a)
like image 34
SlimJim Avatar answered Mar 02 '26 09:03

SlimJim