How to smooth nested list in python?

How can I convert:

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

in

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

in python (no need to sort it, just flatten it)?

I have tried many things but cannot find how to solve this.

+7
python
source share
2 answers

Solved with a 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 for 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']] 
+2
source share

The recursive function really shines here:

 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.

+1
source share

All Articles