1

Basically what I am trying is seeing if I can flatten down nested lists when the list contains 1 single item which is another list. For example take this data structure:

[['a', 'b', 'c', [['d', 'e', 'f']]]]

The ideal format of the data would be:

['a', 'b', 'c', ['d', 'e', 'f']]

This nesting can go any amount of levels deep but just need to flatten out single list data. Anyone know a way of doing this? The closest I got with answers on SO was: Flattening a list recursively But this completely flattens the list as a whole.

Yonathan
  • 1,253
  • 1
  • 17
  • 29
  • So if the nested list have more than two elements you don't want to flatten it? – Dani Mesejo Dec 05 '18 at 23:15
  • No, it is an artifact of the ingested data. If it would be something like `[['a', 'b', 'c'], 'd']` it should not be flattened, its a very exact case. – Yonathan Dec 05 '18 at 23:17

2 Answers2

2

You can use a recursive function that specifically tests if there's only one item in the given list and if that one item is a list, and if so, skips yielding that list:

def simplify(l):
    if len(l) == 1 and isinstance(l[0], list):
        yield from simplify(l[0])
    else:
        for i in l:
            yield list(simplify(i)) if isinstance(i, list) else i

so that:

list(simplify([['a', 'b', 'c', [['d', 'e', 'f']]]]))

returns:

['a', 'b', 'c', ['d', 'e', 'f']]
blhsing
  • 91,368
  • 6
  • 71
  • 106
0

A recursive function can do this:

def flatten(l: list):
    if len(l) == 1:
        if isinstance(l[0], list):
            l = l[0]
    for i, elem in enumerate(l):
        if isinstance(type(elem), list):
            l[i] = flatten(elem)
    return l
Axel Puig
  • 1,304
  • 9
  • 19