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

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

关于python - 如何在 python 中展平嵌套列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21631278/

相关文章:

python - 如何通过 Python 使用亚马逊产品广告 API 5?

python - 我们可以在webapp2中使用i18n进行全局设置吗?

python - 字典:从一系列字典值中的第二个条目中减去第一个条目

python - Windows 7 中的 Django 1.4 "No FlatPage matches the given query"

python - 每天运行 python 脚本的最佳方式是什么?

python - 当 Python 更新时,我是否需要更新我的程序?

python - 是否可以停止 sqlite 将双引号标识符视为字符串?

python - 在 python 中记录混淆

python - Python 如何知道一段代码在循环中?

python - 如何使背景颜色与表单背景颜色相同?