如何在python中展平嵌套列表?

时间:2014-02-07 15:15:08

标签: 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中

(它不需要排序,只需要展平)?

我尝试了很多东西,却找不到如何解决这个问题。

2 个答案:

答案 0 :(得分:2)

用递归生成器解决

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']]

答案 1 :(得分:1)

这是递归函数真正发挥作用的地方:

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, [])

我认为应该这样做。