本文介绍了展平一个可迭代的迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何编写 function 来返回嵌套在可迭代对象中的每个值?

How can I write function which should return every value nested in an iterable?

以下是我要完成的任务的示例:

Here's an example of what I'm trying to accomplish:

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 用户为此任务内置了:

Python 2 users have a built-in for this task:

from compiler.ast import flatten

不幸的是,它已在 python 3 中删除.不过你可以自己滚动:

Unfortunately, it has been removed in python 3. You can roll your own though:

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

这篇关于展平一个可迭代的迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 08:45