Python 3替代已弃用的compile.ast展平功能
问题内容:
>>> from compiler.ast import flatten
>>> flatten(["junk",["nested stuff"],[],[[]]])
['junk', 'nested stuff']
我知道有一些堆栈溢出的答案可以使列表变平,但是我希望使用pythonic标准包,“一种,最好只有一种明显的方式”来做到这一点。
问题答案:
您声明的函数需要一个嵌套列表,并将其展平为新列表。
要将任意嵌套的列表平整到新列表中,可以按预期在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)