4

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

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

PS 这个问题的答案不适用于异构列表。在 Python 中展平一个浅列表

4

11 回答 11

10

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

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)
于 2012-05-17T08:36:41.573 回答
5

它可以整齐地在一行中使用numpy

import numpy as np
np.hstack(l)

你最终得到一个 ndarray

array([  35,   53,  525, 6743,   64,   63,  743,  754,  757])
于 2012-05-17T08:33:02.387 回答
4
>>> data = [35,53,[525,6743],64,63,[743,754,757]]
>>> def flatten(L):
        for item in L:
            if isinstance(item,list):
                for subitem in item:
                    yield subitem
            else:
                yield item


>>> list(flatten(data))
[35, 53, 525, 6743, 64, 63, 743, 754, 757]

这是用于代码高尔夫目的的单行版本(看起来不太好:D)

>>> [y for x in data for y in (x if isinstance(x,list) else [x])]
[35, 53, 525, 6743, 64, 63, 743, 754, 757]
于 2012-05-17T08:40:45.210 回答
3
l = [35,53,[525,6743],64,63,[743,754,757]]
outputList = []

for i in l:
    if isinstance(i, list):
        outputList.extend(i)
    else:
        outputList.append(i)
于 2012-05-17T08:22:56.383 回答
1

这是一个oneliner,基于您提到的问题

list(itertools.chain(*((sl if isinstance(sl, list) else [sl]) for sl in l)))

更新:以及完全基于迭代器的版本:

from itertools import imap, chain
list(chain.from_iterable(imap(lambda x: x if isinstance(x, list) else [x], l)))
于 2012-05-17T08:24:35.010 回答
1
outputList = []
for e in l:
    if type(e) == list:
        outputList += e
    else:
        outputList.append(e)

>>> outputList
[35, 53, 525, 6743, 64, 63, 743, 754, 757]
于 2012-05-17T08:24:41.787 回答
0
def nchain(iterable):
    for elem in iterable:
        if type(elem) is list:
            for elem2 in elem:
                yield elem2
        else:
            yield elem
于 2012-05-17T08:28:36.740 回答
0

允许无限树深度的递归函数:

def flatten(l):
    if isinstance(l,(list,tuple)):
        if len(l):
            return flatten(l[0]) + flatten(l[1:])
        return []
    else:
        return [l]

>>>flatten([35,53,[525,[1,2],6743],64,63,[743,754,757]])
[35, 53, 525, 1, 2, 6743, 64, 63, 743, 754, 757]

我试图避免 isinstance 以允许泛型类型,但旧版本会在字符串上无限循环。现在它正确地展平了字符串(现在不是字符,而是假装字符串是标量)。

于 2012-05-17T08:39:27.937 回答
0
>>> L = [35,53,[525,6743],64,63,[743,754,757]]
>>> K = []
>>> [K.extend([i]) if type(i) == int else K.extend(i) for i in L ]
[None, None, None, None, None, None]
>>> K
[35, 53, 525, 6743, 64, 63, 743, 754, 757]
于 2012-05-17T13:50:16.777 回答
0

此解决方案仅适用于您的特定情况(列表中的标量)并假定标量是整数。这是一个糟糕的解决方案,但它非常短。

outputlist = map(int,",".split(str(L).replace("[","").replace("]","")))
于 2015-02-26T21:00:10.367 回答
0

答案很简单。利用递归。

def flatten(nst_lst, final_list):

    for val in nst_lst:
        if isinstance(val, list):
            flatten(val, final_list)
        else:
            final_list.append(val)
    return final_list

#Sample usage
fl_list = []
lst_to_flatten = [["this",["a",["thing"],"a"],"is"],["a","easy"]]

print(flatten(lst_to_flatten, fl_list))
于 2017-02-10T06:13:02.733 回答