How to flatten a 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']
]
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.
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.
链接地址: http://www.djcxy.com/p/18892.html上一篇: Sitecore 7 ContentSearch API是否删除查询中的停用词?
下一篇: 如何在python中拼合一个嵌套列表?