p priyanka p priyanka - 3 months ago 29
Python Question

How to convert sublist to list

I am having the list like this below,

[
'August 28, 2017',
'gilbert arizona',
'33.3528264',
'-111.789027',
'1236 Feet',
"[u' ASCE 7* Ground Snow LoadElevation 2,000 feet', u' Ground Snow Load is0 psf']"
]


I want convert this to the form

[
'August 28, 2017',
'gilbert arizona',
'33.3528264',
'-111.789027',
'1236 Feet',
'ASCE 7* Ground Snow LoadElevation 2,000 feet',
' Ground Snow Load is0 psf'
]

Answer Source

I agree with cricket_007, you really should address this at the source, as it's poorly formed data and any solution will be brittle and prone to breaking. That said, if you just need something quick-and-dirty, the following should do the trick while avoiding using the unsafe eval function.

from ast import literal_eval

def flatten(iterable):
    result = []

    for item in iterable:
        try:
            item_eval = literal_eval(item)
            if not isinstance(item_eval, list):
                raise ValueError()
        except (ValueError, SyntaxError):
            result.append(item)
        else:
            result.extend(flatten(item_eval))

    return result


>>> data = [
...     'August 28, 2017',
...     'gilbert arizona',
...     '33.3528264',
...     '-111.789027',
...     '1236 Feet',
...     "[u'  ASCE 7* Ground Snow LoadElevation 2,000 feet', u' Ground Snow Load is0 psf']"
... ]

>>> flatten(data)
['August 28, 2017', 'gilbert arizona', '33.3528264', '-111.789027', '1236 Feet', u'  ASCE 7* Ground Snow LoadElevation 2,000 feet', u' Ground Snow Load is0 psf']