Python 3 替换已弃用的 compiler.ast flatten 函数 [英] Python 3 replacement for deprecated compiler.ast flatten function
问题描述
我知道列表扁平化有一些堆栈溢出的答案,但我希望 Pythonic 的标准包,一种,最好只有一种,明显的方法"来做到这一点.
您声明的函数采用嵌套列表并将其展平为新列表.
要将任意嵌套的列表展平为新列表,这在 Python 3 上如您所愿:
导入集合定义展平(x):结果 = []对于 x 中的 el:如果 isinstance(x, collections.Iterable) 而不是 isinstance(el, str):result.extend(flatten(el))别的:result.append(el)返回结果打印(扁平化([垃圾",[嵌套的东西"],[],[[]]]))
打印:
['垃圾','嵌套的东西']
如果你想要一个做同样事情的生成器:
def flat_gen(x):def iselement(e):返回 not(isinstance(e, collections.Iterable) 而不是 isinstance(e, str))对于 x 中的 el:如果 iselement(el):产量 el别的:对于 flat_gen(el) 中的 sub:yield sub打印(列表(flat_gen([垃圾",[嵌套的东西"],[],[[[],['深']]]])))# ['垃圾','嵌套的东西','深']
对于 Python 3.3 及更高版本,请改用 yield from循环:
def flat_gen(x):def iselement(e):返回 not(isinstance(e, collections.Iterable) 而不是 isinstance(e, str))对于 x 中的 el:如果 iselement(el):产量 el别的:flat_gen(el) 的产量
What's the recommended way to flatten nested lists since the deprecation of the compiler package?
>>> from compiler.ast import flatten
>>> flatten(["junk",["nested stuff"],[],[[]]])
['junk', 'nested stuff']
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.
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"],[],[[]]]))
Prints:
['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']
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 替换已弃用的 compiler.ast flatten 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!