Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to flatten a nested list in python?

Tags:

python

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.

like image 826
jbrown Avatar asked Feb 07 '14 15:02

jbrown


People also ask

How do I merge a nested list into one list in Python?

Method 3: Using sum() function Use the sum() function to concatenate nested lists to a single list by passing an empty list as a second argument to it.


2 Answers

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']]
like image 112
Imran Avatar answered Oct 07 '22 05:10

Imran


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.

like image 20
wheaties Avatar answered Oct 07 '22 05:10

wheaties