如何扁平化包含多种数据类型的列表(整数,元组)

9 投票
5 回答
1849 浏览
提问于 2025-04-17 23:21

假设我有一个列表,里面包含一个或多个元组:

[0, 2, (1, 2), 5, 2, (3, 5)]

有没有什么好的方法可以把这些元组去掉,只留下整数列表呢?

[0, 2, 1, 2, 5, 2, 3, 5]

5 个回答

1

你可以使用我这个flatten函数,它在我的funcy库里。

from funcy import flatten
flat_list = flatten(your_list)

你也可以看看它的实现代码

1

这是一个更通用的递归解决方案,可以适用于任何可迭代的对象(除了字符串)和任意深度的元素:

import collections

def flatten(iterable):
    results = []
    for i in iterable:
        if isinstance(i, collections.Iterable) and not isinstance(i, basestring):
            results.extend(flatten(i))
        else:
            results.append(i)
    return results

使用方法如下:

>>> flatten((1, 2, (3, 4), ('happy')))
[1, 2, 3, 4, 'happy']
>>> flatten((1, 2, (3, 4, (5, 6)), ('happy'), {'foo': 'bar', 'baz': 123}))
[1, 2, 3, 4, 5, 6, 'happy', 'foo', 'baz']
1
def untuppleList(lst):
    def untuppleList2(x):
        if isinstance(x, tuple):
            return list(x)
        else:
            return [x]
    return [y for x in lst for y in untuppleList2(x)]

然后你可以这样做:untuppleList([0, 2, (1, 2), 5, 2, (3, 5)])

5

使用嵌套的列表推导式:

>>> lst = [0, 2, (1, 2), 5, 2, (3, 5)]
>>> [y for x in lst for y in (x if isinstance(x, tuple) else (x,))]
[0, 2, 1, 2, 5, 2, 3, 5]
6

其中一个解决方案是使用 itertools.chain

>>> from itertools import chain
>>> l = [0, 2, (1, 2), 5, 2, (3, 5)]
>>> list(chain(*(i if isinstance(i, tuple) else (i,) for i in l)))
[0, 2, 1, 2, 5, 2, 3, 5]

撰写回答