1

Say I have a list in Python:

l = [1, 2, 3, [a, [[9, 10, 11]], c, d], 5, [e, f, [6, 7, [8]]]]

I would like to clean all the nested lists so that, if they are of length 1 (just one item), the are "pulled up" out of the list, such that the revised list would look like:

l = [1, 2, 3, [a, [9, 10, 11], c, d], 5, [e, f, [6, 7, 8]]]

Naturally I can just check if len == 1 and replace that index with its contents, but... Is there a built-in way to do this?

4

1 回答 1

2

您可以使用递归函数:

def expand_singles(item):
    if isinstance(item, list):
        if len(item) == 1:
            return expand_singles(item[0])
        return [expand_singles(i) for i in item]
    return item

演示:

>>> def expand_singles(item):
...     if isinstance(item, list):
...         if len(item) == 1:
...             return expand_singles(item[0])
...         return [expand_singles(i) for i in item]
...     return item
... 
>>> l = [1, 2, 3, ['a', [[9, 10, 11]], 'c', 'd'], 5, ['e', 'f', [6, 7, [8]]]]
>>> expand_singles(l)
[1, 2, 3, ['a', [9, 10, 11], 'c', 'd'], 5, ['e', 'f', [6, 7, 8]]]
于 2014-10-28T22:14:45.857 回答