用Python展平任意嵌套列表的最快方法是什么? [英] What is the fastest way to flatten arbitrarily nested lists in Python?

查看:135
本文介绍了用Python展平任意嵌套列表的最快方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
在Python中添加浅表
用Python整理的(不规则的)列表列表

Possible Duplicate:
Flattening a shallow list in Python
Flatten (an irregular) list of lists in Python

问题不是如何做到这一点-这已经问题<中讨论了 /a>-问题是,最快方法是什么?

The question is not how to do it - this has been discussed in other questions - the question is, which is the fastest method?

我以前找到了解决方案,但我想知道最快的解决方案是将包含其他任意长度列表的列表展平.

I've found solutions before, but I'm wondering what the fastest solution is to flatten lists which contain other lists of arbitrary length.

例如:

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

将成为:

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

可以有无限多个级别.某些列表对象可以是字符串,在输出列表中不得将其展平为它们的顺序字符.

There can be infinitely many levels. Some of the list objects can be strings, which mustn't be flattened into their sequential characters in the output list.

推荐答案

这是一种对字符串友好的递归方法:

Here's a recursive approach that is string friendly:

nests = [1, 2, [3, 4, [5],['hi']], [6, [[[7, 'hello']]]]]

def flatten(container):
    for i in container:
        if isinstance(i, (list,tuple)):
            for j in flatten(i):
                yield j
        else:
            yield i

print list(flatten(nests))

返回:

[1, 2, 3, 4, 5, 'hi', 6, 7, 'hello']

请注意,这并不能保证速度或开销的使用,但是说明了一种递归解决方案,希望会对您有所帮助.

Note, this doesn't make any guarantees for speed or overhead use, but illustrates a recursive solution that hopefully will be helpful.

这篇关于用Python展平任意嵌套列表的最快方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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