删除所有空的嵌套列表

时间:2013-12-04 05:57:36

标签: python nested-lists

如何从此列表中:

list = [
    [],
    ['', 'subitem'],
    [[]],
    'item',
    [
        'item',
        'item',
        [''],
        []
    ],
    []
]

我可以得到这个:

list = [
    ['subitem'],
    'item',
    [
        'item',
        'item'
    ]
]

如何递归删除所有空嵌套列表,零字符串和嵌套零字符串列表?

4 个答案:

答案 0 :(得分:8)

递归:

def remove_lst(lst):
    if not isinstance(lst, list):
        return lst
    else:
        return [x for x in map(remove_lst, lst) if (x != [] and x != '')]

答案 1 :(得分:3)

def purify(l):
    for (i, sl) in enumerate(l):
        if type(sl) == list:
            l[i] = purify(sl)
    return [i for i in l if i != [] and i != '']

l1 = [ [], ['', 'subitem'], [[]], 'item', [ 'item', 'item', [''], [] ], [] ]
print purify(l1)

打印:

[['subitem'], 'item', ['item', 'item']]

答案 2 :(得分:3)

单行:

def remove_empty(l):
    return tuple(filter(lambda x:not isinstance(x, (str, list, tuple)) or x, (remove_empty(x) if isinstance(x, (tuple, list)) else x for x in l)))

答案 3 :(得分:1)

也许是这样的?

#!/usr/local/cpython-3.3/bin/python

'''Demonstrate a way of removing empty lists and empty strings from a nested list'''

import pprint

def remove_empty_recursive(input_obj):
    '''Remove empty lists and strings - worker function'''
    if isinstance(input_obj, str):
        if input_obj:
            # it's a nonempty string, pass it through
            return input_obj
        else:
            # string is empty, delete it
            return None
    elif isinstance(input_obj, list):
        if input_obj:
            new_obj = []
            for element in input_obj:
                subresult = remove_empty_recursive(element)
                if subresult is None:
                    pass
                else:
                    new_obj.append(subresult)
            if new_obj:
                return new_obj
            else:
                return None
        else:
            return None

def remove_empty(list_):
    '''Remove empty lists and strings - user callable portion'''
    result = remove_empty_recursive(list_)
    return result

def for_comparison():
    '''Show what the O.P. wanted, for comparison's sake'''
    list_ = [
        ['subitem'],
        'item',
        [
            'item',
            'item'
        ]
    ]
    return pprint.pformat(list_)

def main():
    '''Main function'''

    list_ = [
        [],
        ['', 'subitem'],
        [[]],
        'item',
        [
            'item',
            'item',
            [''],
            []
        ],
        []
    ]

    result = remove_empty(list_)
    print('actual result:')
    pprint.pprint(result)
    print('desired result:')
    print(for_comparison())

main()

如果不是这样,你可能想要分享一个更详细的例子,说明这个失败了。