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

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

问题描述

可能的重复:
在 Python 中展平浅表
在 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天全站免登陆