如何在python中拼合一个嵌套列表?
我如何转换:
THIS =
['logging',
['logging', 'loggers',
['logging', 'loggers', 'MYAPP',
['logging', 'loggers', 'MYAPP', '-handlers'],
['logging', 'loggers', 'MYAPP', 'propagate']
]
],
['logging', 'version']
]
成:
THAT = [
['logging'],
['logging', 'version'],
['logging', 'loggers'],
['logging', 'loggers', 'MYAPP'],
['logging', 'loggers', 'MYAPP', '-handlers'],
['logging', 'loggers', 'MYAPP', 'propagate']
]
在Python中(它不需要排序,只是变平)?
我尝试了很多东西,但找不到如何解决这个问题。
用递归生成器解决
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
根据您的输入测试:
from pprint import pprint
>>> pprint(sorted(flatten(THIS)))
[['logging'],
['logging', 'loggers'],
['logging', 'loggers', 'MYAPP'],
['logging', 'loggers', 'MYAPP', '-handlers'],
['logging', 'loggers', 'MYAPP', 'propagate'],
['logging', 'version']]
这是递归函数真正发挥的地方:
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, [])
我相信这应该可以做到。
链接地址: http://www.djcxy.com/p/18891.html上一篇: How to flatten a nested list in python?
下一篇: Move .git into a different directory than the source it manages