拼合不规则的列表 [英] Flatten an irregular list of lists

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

问题描述

是的,我知道此主题之前已经讨论过(此处此处

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中添加的可迭代的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

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

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

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