python展开list嵌套,并解决from compiler.ast import flatten报错ModuleNotFoundError: No module named ‘compiler‘

用途:
将类似:[[['a', 'b'], 'c'], ['A', 'B', 'C'], '1', '2', '3']
展开为:['a', 'b', 'c', 'A', 'B', 'C', '1', '2', '3']

python2与报错解决

在python2中可以使用:

from compiler.ast import flatten

list_example = [[['a', 'b'], 'c'], ['A', 'B', 'C'], '1', '2', '3']
print(flatten(list_example))

python3

使用:

import collections.abc


def flatten(x):
    result = []
    for el in x:
        if isinstance(x, collections.abc.Iterable) and not isinstance(el, str):
            result.extend(flatten(el))
        else:
            result.append(el)
    return result


if __name__ == '__main__':
    list_example = [[['a', 'b'], 'c'], ['A', 'B', 'C'], '1', '2', '3']
    print(flatten(list_example))
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
根据引用和引用的内容,你遇到的"ModuleNotFoundError: No module named 'compiler.ast'"是因为Python 3中已废除了compiler模块。在Python 3中,你需要使用其他方法来实现相同的功能。 根据引用中提供的解决方法,你可以使用以下代码来替代在Python 3中废除的compiler模块: ```python import collections def flatten(x): result = [] for el in x: if isinstance(el, collections.Iterable) and not isinstance(el, str): result.extend(flatten(el)) else: result.append(el) return result print(flatten(["junk",["nested stuff"],[],[[]]])) ``` 这个代码将递归地将嵌套的列表展平为一个一维列表。你可以将你的列表作为参数传递给`flatten`函数,并打印结果。 如果你在Python 2中使用了`from compiler.ast import flatten`,可以参考引用中提供的代码,在Python 3中实现相同的功能。 希望这能帮到你!如果还有其他问题,请随时提问。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [ModuleNotFoundError: No module named 'compiler'](https://blog.csdn.net/chenhaojing/article/details/82829611)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [python展开list嵌套,并解决from compiler.ast import flattenModuleNotFoundError: No module named ...](https://blog.csdn.net/weixin_35757704/article/details/120110267)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

呆萌的代Ma

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值