您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python 3替代已弃用的compile.ast展平功能

Python 3替代已弃用的compile.ast展平功能

您声明的函数需要一个嵌套列表,并将其展平为新列表。

要将任意嵌套的列表平整到新列表中,可以按预期在Python 3上运行:

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

print(flatten(["junk",["nested stuff"],[],[[]]]))

印刷品:

['junk', 'nested stuff']

如果您希望生成器执行相同的操作:

def flat_gen(x):
    def iselement(e):
        return not(isinstance(e, collections.Iterable) and not isinstance(e, str))
    for el in x:
        if iselement(el):
            yield el
        else:
            for sub in flat_gen(el): yield sub

print(list(flat_gen(["junk",["nested stuff"],[],[[[],['deep']]]]))) 
# ['junk', 'nested stuff', 'deep']

对于Python 3.3及更高版本,请使用yield from而不是循环:

def flat_gen(x):
    def iselement(e):
        return not(isinstance(e, collections.Iterable) and not isinstance(e, str))
    for el in x:
        if iselement(el):
            yield el
        else:
            yield from flat_gen(el)
python 2022/1/1 18:41:51 有478人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶