Python 把一堆乱七八糟的东西弄平

Python 把一堆乱七八糟的东西弄平,python,python-3.x,Python,Python 3.x,如何编写函数,该函数应返回iterable中嵌套的每个值 以下是我试图实现的一个示例: for i in function([1, 2, [3, 4, (5, 6, 7), 8, 9], 10]): print(i, end=' ') 预期产出: 1 2 3 4 5 6 7 8 9 10 Python 2用户对此任务具有内置的功能: from compiler.ast import flatten 不幸的是,它在Python3中被删除了。不过,您可以自己动手: from colle

如何编写
函数
,该函数应返回iterable中嵌套的每个值

以下是我试图实现的一个示例:

for i in function([1, 2, [3, 4, (5, 6, 7), 8, 9], 10]):
    print(i, end=' ')
预期产出:

1 2 3 4 5 6 7 8 9 10

Python 2用户对此任务具有内置的功能:

from compiler.ast import flatten
不幸的是,它在Python3中被删除了。不过,您可以自己动手:

from collections.abc import Iterable

def flatten(collection):
    for x in collection:
        if isinstance(x, Iterable) and not isinstance(x, (str, bytes)):
            yield from flatten(x)
        else:
            yield x

带有奇怪限制的家庭作业问题需要有趣的答案

import re
def function(L):
    return re.findall("[a-z0-9]+", repr(L))

我想如果你需要这个,你就有问题了。为什么你的问题听起来很像家庭作业问题?为什么“不使用
itertools
?这些工具是标准库的一部分,这是有原因的!请不要在收到答案后删除您的问题。当然,除非你想被禁止再问问题。我想你找到了。加州大学欧文分校,ICS-33,问题#3:装饰器模块(迭代器),额外的学分问题。如果它a)没有从dict中挖掘出值,b)没有中断,那会更有趣0s@wim啊!修复了0和OP的更改,因此没有dicts:)gnibbletastic。。你能告诉我如何使用
re
解析html吗?