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.
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.
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']]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With