Python 3替代已弃用的compile.ast展平函数 [英] Python 3 replacement for deprecated compiler.ast flatten function

查看:80
本文介绍了Python 3替代已弃用的compile.ast展平函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

弃用编译器以来,推荐的扁平化嵌套列表的方法是什么包?

>>> from compiler.ast import flatten
>>> flatten(["junk",["nested stuff"],[],[[]]])
['junk', 'nested stuff']

我知道有一些堆栈溢出的答案可以使列表变平,但是我希望使用pythonic的标准包,一种,最好只有一种明显的方式"来做到这一点.

I know that there are a few stack overflow answers for list flattening, but I'm hoping for the pythonic, standard package, "one, and preferably only one, obvious way" to do this.

推荐答案

您声明的函数采用嵌套列表并将其展平为新列表.

Your stated function takes a nested list and flattens that into a new list.

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

To flatten an arbitrarily nested list into a new list, this works on Python 3 as you expect:

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

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

If you want a generator that does the same thing:

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和更高版本,请使用收益循环:

For Python 3.3 and later, use yield from instead of the loop:

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 3替代已弃用的compile.ast展平函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆