如何在python中将列表的异构列表展平为单个列表? [英] How to flatten a hetrogenous list of list into a single list in python?

查看:93
本文介绍了如何在python中将列表的异构列表展平为单个列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象列表,其中对象可以是列表或标量.我想要一个只有标量的扁平化列表. 例如:

I have a list of objects where objects can be lists or scalars. I want an flattened list with only scalars. Eg:

L = [35,53,[525,6743],64,63,[743,754,757]]
outputList = [35,53,525,6743,64,63,743,754,757]

P.S.该问题的答案不适用于异构列表. 在Python中添加浅表

P.S. The answers in this question does not work for heterogeneous lists. Flattening a shallow list in Python

推荐答案

这是一个相对简单的递归版本,它将使列表的任何深度变平

Here is a relatively simple recursive version which will flatten any depth of list

l = [35,53,[525,6743],64,63,[743,754,757]]

def flatten(xs):
    result = []
    if isinstance(xs, (list, tuple)):
        for x in xs:
            result.extend(flatten(x))
    else:
        result.append(xs)
    return result

print flatten(l)

这篇关于如何在python中将列表的异构列表展平为单个列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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