如何将子列表转换为列表

时间:2017-08-28 07:46:48

标签: python python-3.x list

我有以下列表,

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

我希望将其转换为

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

1 个答案:

答案 0 :(得分:4)

我同意cricket_007,你真的应该在源头解决这个问题,因为它的数据形成不好,任何解决方案都会很脆弱,容易破解。也就是说,如果你只需要快速和肮脏的东西,以下应该可以避免使用不安全的eval函数。

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