以此为本,以此为本,以此为本,以此为本,以此为本,以此为本,以此为本。


如果您的列表来自列表理解,问题可以通过纠正理解更简单/直接解决;请参见Python列表理解;压缩列表?

在这里,最受欢迎的解决方案通常只包含一个“层”的清单。 查看清单不规则(自愿清单)的清单,解决方案完全清单一个深度清单的结构(重复,一般)。


当前回答

如果你有一个Numpy Array A:

a = np.array([[1,2], [3,4]])
a.flatten('C')

生产:

[1, 2, 3, 4]

np.flatten 也接受其他参数:

C: F A K

有关参数的详细信息可在这里找到。

其他回答

你的功能不起作用的原因是因为延伸延伸一个序列在现场,并且不会返回它。

reduce(lambda x,y: x.extend(y) or x, l)

注意:扩展比 + 列表更有效。

我会建议使用发电机与产量声明和产量从。

from collections.abc import Iterable

def flatten(items, ignore_types=(bytes, str)):
    """
       Flatten all of the nested lists to the one. Ignoring flatting of iterable types str and bytes by default.
    """
    for x in items:
        if isinstance(x, Iterable) and not isinstance(x, ignore_types):
            yield from flatten(x)
        else:
            yield x

values = [7, [4, 3, 5, [7, 3], (3, 4), ('A', {'B', 'C'})]]

for v in flatten(values):
    print(v)

我想要一個解決方案,可以處理多種<unk>(<unk>,<unk>,<unk>,<unk>),<unk>,<unk>,<unk>,<unk>,<unk>,<unk>,<unk>,<unk>,<unk>,<unk>,<unk>,<unk>,<unk>。

这就是我所带来的:

def _flatten(l) -> Iterator[Any]:
    stack = l.copy()
    while stack:
        item = stack.pop()
        if isinstance(item, list):
            stack.extend(item)
        else:
            yield item


def flatten(l) -> Iterator[Any]:
    return reversed(list(_flatten(l)))

和测试:

@pytest.mark.parametrize('input_list, expected_output', [
    ([1, 2, 3], [1, 2, 3]),
    ([[1], 2, 3], [1, 2, 3]),
    ([[1], [2], 3], [1, 2, 3]),
    ([[1], [2], [3]], [1, 2, 3]),
    ([[1], [[2]], [3]], [1, 2, 3]),
    ([[1], [[[2]], [3]]], [1, 2, 3]),
])
def test_flatten(input_list, expected_output):
    assert list(flatten(input_list)) == expected_output

你可以简单地使用Pandas这样做:

import pandas as pd
pd.Series([[1, 2, 3], [4, 5, 6], [7], [8, 9]]).sum()

如果我想添加一些东西到以前的答案,这里是我的重复滑板功能,可以滑板不只是滑板列表,但也任何提供的容器或一般任何物品,可以扔出物品。

def flatten(iterable):
    # These types won't considered a sequence or generally a container
    exclude = str, bytes

    for i in iterable:
        try:
            if isinstance(i, exclude):
                raise TypeError
            iter(i)
        except TypeError:
            yield i
        else:
            yield from flatten(i)

这样,你可以排除你不想要的类型,如 str 或其他。

想法是,如果一个对象可以通过 iter(),它已经准备好产生物品,所以 iterable 甚至可以作为一个对象具有发明器表达式。

有人可以争论:为什么你写了这么一般的,当OP没有要求它?OK,你是对的,我只是觉得这可能帮助某人(就像它为我做的那样)。

测试案例:

lst1 = [1, {3}, (1, 6), [[3, 8]], [[[5]]], 9, ((((2,),),),)]
lst2 = ['3', B'A', [[[(i ** 2 for i in range(3))]]], range(3)]

print(list(flatten(lst1)))
print(list(flatten(lst2)))

出口:

[1, 3, 1, 6, 3, 8, 5, 9, 2]
['3', b'A', 0, 1, 4, 0, 1, 2]