展平不规则的列表列表 [英] Flatten an irregular list of lists

查看:29
本文介绍了展平不规则的列表列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是的,我知道之前已经讨论过这个主题(此处此处此处此处),但据我所知,除一个之外,所有解决方案都在如下列表中失败:

Yes, I know this subject has been covered before (here, here, here, here), but as far as I know, all solutions, except for one, fail on a list like this:

L = [[[1, 2, 3], [4, 5]], 6]

所需的输出在哪里

[1, 2, 3, 4, 5, 6]

或者甚至更好,一个迭代器.我看到的唯一适用于任意嵌套的解决方案是在这个问题:

Or perhaps even better, an iterator. The only solution I saw that works for an arbitrary nesting is found in this question:

def flatten(x):
    result = []
    for el in x:
        if hasattr(el, "__iter__") and not isinstance(el, basestring):
            result.extend(flatten(el))
        else:
            result.append(el)
    return result

flatten(L)

这是最好的模型吗?我忽略了什么吗?有什么问题吗?

Is this the best model? Did I overlook something? Any problems?

推荐答案

使用生成器函数可以使您的示例更易于阅读,并可能提高性能.

Using generator functions can make your example a little easier to read and probably boost the performance.

def flatten(l):
    for el in l:
        if isinstance(el, collections.Iterable) and not isinstance(el, basestring):
            for sub in flatten(el):
                yield sub
        else:
            yield el

我使用了 2.6 中添加的 Iterable ABC.

I used the Iterable ABC added in 2.6.

在 Python 3 中,basestring 不再存在,但您可以使用 strbytes 的元组在那里获得相同的效果.

In Python 3, the basestring is no more, but you can use a tuple of str and bytes to get the same effect there.

yield from 运算符一次从生成器返回一个项目.这个委托给子生成器的语法是在 3.3 中添加的>

The yield from operator returns an item from a generator one at a time. This syntax for delegating to a subgenerator was added in 3.3

from collections.abc import Iterable

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

这篇关于展平不规则的列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆