p priyanka
p priyanka

Reputation: 129

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'
]

Upvotes: 1

Views: 355

Answers (1)

DBrowne
DBrowne

Reputation: 703

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']

Upvotes: 4

Related Questions