1

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'
]
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
p priyanka
  • 129
  • 1
  • 9

1 Answers1

4

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']
DBrowne
  • 683
  • 4
  • 12
  • How to remove the u' from the flatten(data). Please help me – p priyanka Aug 28 '17 at 09:16
  • The `u` just denotes that it's a unicode string. You don't need to get rid of it. if you print the list element it won't be included. – DBrowne Aug 28 '17 at 09:27
  • result.append(str(item)) try this u' will be removed instead of result.append(item) – keshaw Aug 28 '17 at 09:56
  • The `u` will show up if you print the whole list, but not if you just print an individual element. As I said, it's just telling you that the string is `unicode`. The `u` isn't actually part of the data, you don't need to worry about it. – DBrowne Aug 28 '17 at 10:16