8

How can I convert:

THIS = \
['logging',
 ['logging', 'loggers',
  ['logging', 'loggers', 'MYAPP',
   ['logging', 'loggers', 'MYAPP', '-handlers'],
   ['logging', 'loggers', 'MYAPP', 'propagate']
  ]
 ],
 ['logging', 'version']
]

into:

THAT = [
    ['logging'],
    ['logging', 'version'],
    ['logging', 'loggers'],
    ['logging', 'loggers', 'MYAPP'],
    ['logging', 'loggers', 'MYAPP', '-handlers'],
    ['logging', 'loggers', 'MYAPP', 'propagate']
]

in python (it doesn't need to be sorted, just flattened)?

I've tried lots of things but can't find how to solve this.

jbrown
  • 7,518
  • 16
  • 69
  • 117
  • 1
    http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python – dstromberg Feb 07 '14 at 15:24
  • 1
    See [this question](http://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python), especially [this answer](http://stackoverflow.com/a/406822/1535629). – senshin Feb 07 '14 at 15:24
  • See also: http://stackoverflow.com/questions/11377208/recursive-generator-for-flattening-nested-lists?rq=1 – wheaties Feb 07 '14 at 15:39
  • Does this answer your question? [How do I make a flat list out of a list of lists?](https://stackoverflow.com/questions/952914/how-do-i-make-a-flat-list-out-of-a-list-of-lists) – questionto42 Jul 08 '22 at 18:38

2 Answers2

3

Solved with recursive generator

def flatten(items):
    non_list_items = []

    for item in items:
        if isinstance(item, list):
            for inner_item in flatten(item):
                yield inner_item
        else:
            non_list_items.append(item)

    yield non_list_items

Testing against your input:

from pprint import pprint

>>> pprint(sorted(flatten(THIS)))
[['logging'],
 ['logging', 'loggers'],
 ['logging', 'loggers', 'MYAPP'],
 ['logging', 'loggers', 'MYAPP', '-handlers'],
 ['logging', 'loggers', 'MYAPP', 'propagate'],
 ['logging', 'version']]
Imran
  • 87,203
  • 23
  • 98
  • 131
2

This is where a recursive function really shines:

def flatten(myList):
  def inner(current, acc):
    items = []
    for x in myList:
      if isinstance(x, list):
        acc.extend(inner(x, []))
      else:
        items.append(x)
    acc.extend(items)
    return acc

  return inner(myList, [])

which I believe should do the trick.

wheaties
  • 35,646
  • 15
  • 94
  • 131