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


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

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


当前回答

我创建了一点功能,基本上可以平滑任何东西. 你可以用管道:管道安装平滑一切

from flatten_everything import flatten_everything
withoutprotection=list(
    flatten_everything(
        [
            1,
            1,
            2,
            [3, 4, 5, [6, 3, [2, 5, ["sfs", "sdfsfdsf",]]]],
            1,
            3,
            34,
            [
                55,
                {"brand": "Ford", "model": "Mustang", "year": 1964, "yearxx": 2020},
                pd.DataFrame({"col1": [1, 2], "col2": [3, 4]}),
                {"col1": [1, 2], "col2": [3, 4]},
                55,
                {"k32", 34},
                np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]),
                (np.arange(22), np.eye(2, 2), 33),
            ],
        ]
    )
)
print(withoutprotection)
output:
[1, 1, 2, 3, 4, 5, 6, 3, 2, 5, 'sfs', 'sdfsfdsf', 1, 3, 34, 55, 'Ford', 'Mustang', 1964, 2020, 1, 2, 3, 4, 1, 2, 3, 4, 55, 34, 'k32', 1, 2, 3, 4, 5, 6, 7, 8, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 1.0, 0.0, 0.0, 1.0, 33]

你甚至可以保护物体免受闪烁:

from flatten_everything import ProtectedDict,ProtectedList,ProtectedTuple
withprotection=list(
    flatten_everything(
        [
            1,
            1,
            2,
            [3, 4, 5, [6, 3, [2, 5, ProtectedList(["sfs", "sdfsfdsf",])]]],
            1,
            3,
            34,
            [
                55,
                ProtectedDict({"brand": "Ford", "model": "Mustang", "year": 1964, "yearxx": 2020}),
                pd.DataFrame({"col1": [1, 2], "col2": [3, 4]}),
                {"col1": [1, 2], "col2": [3, 4]},
                55,
                {"k32", 34},
                np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]),
                ProtectedTuple((np.arange(22), np.eye(2, 2), 33)),
            ],
        ]
    )
)
print(withprotection)
output:
[1, 1, 2, 3, 4, 5, 6, 3, 2, 5, ['sfs', 'sdfsfdsf'], 1, 3, 34, 55, {'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'yearxx': 2020}, 1, 2, 3, 4, 1, 2, 3, 4, 55, 34, 'k32', 1, 2, 3, 4, 5, 6, 7, 8, (array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,17, 18, 19, 20, 21]), array([[1., 0.], [0., 1.]]), 33)]

其他回答

作者的注意事项:这是非常不有效的,但有趣,因为单曲是惊人的。

>>> xss = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
>>> sum(xss, [])
[1, 2, 3, 4, 5, 6, 7, 8, 9]

总数是不可分割 xss 的元素,并使用第二个论点作为总数的初始值(默认初始值为0,这不是列表)。

因為你們是清清清清清清清清清清清清清清清清清清清清清清清清清清清清清清清清清清清。

请注意,它只适用于列表列表,对于列表列表列表,您将需要另一个解决方案。

np.hstack(listoflist).tolist()

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

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]

如果你有一个Numpy Array A:

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

生产:

[1, 2, 3, 4]

np.flatten 也接受其他参数:

C: F A K

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

不是一个单行,但看到所有的答案在这里,我猜这个漫长的列表错过了一些模式匹配,所以在这里它是:)

这两种方法可能不是有效的,但无论如何,它很容易阅读(至少对我来说,也许我被功能编程所困扰):

def flat(x):
    match x:
        case []:
            return []
        case [[*sublist], *r]:
            return [*sublist, *flat(r)]

第二版考虑了列表列表的列表......不管什么:

def flat(x):
    match x:
        case []:
            return []
        case [[*sublist], *r]:
            return [*flat(sublist), *flat(r)]
        case [h, *r]:
            return [h, *flat(r)]