要将任意嵌套的列表平整到新列表中,可以按预期在Python 3上运行:
import collectionsdef 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 resultprint(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 subprint(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)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)