扁平化一个包含整数和列表的列表

2 投票
5 回答
1465 浏览
提问于 2025-04-18 01:50

假设输入是:

[1, [3, 6], 9, [2, [1, 3]], [4, [1], 5], [6], 1, [[2]]]

期望的输出是:

[1,1,1,1,2,2,3,3,4,5,6,6,9]

我该如何把这个列表变平,但又不去掉重复的元素呢?

我现在的情况是:

def flatten(lst):
    nlist = []
    for item in lst:
        nlist = nlist + [item]
    return nlist

我最开始的想法是把元素重新放到一个新的列表里,这样就能得到期望的输出。但是结果并不理想,我得到了:

我得到的是:

[1, [3, 6], 9, [2, [1, 3]], [4, [1], 5], [6], 1, [[2]]]

我正在使用 IDLE 3.3,而且我完全是个新手。如果可以的话,请告诉我怎么手动定义这个,而不是使用内置的函数,也就是说用递归或者迭代的方法。谢谢大家!!

5 个回答

0

在 Python 2.x 版本中,你可以使用 flatten 方法,这个方法在 compiler.ast 模块里(注意:从 2.6 版本开始,这个编译器包在 Python 3 中就被移除了)。使用方法如下:

from compiler.ast import flatten

l = [1, [3, 6], 9, [2, [1, 3]], [4, [1], 5], [6], 1, [[2]]]
flattened = flatten(l)
sorted_list = sorted(flattened)

在 Python 3 中,如果你想把一个任意嵌套的列表变平,可以使用以下代码,具体内容可以在 这里 找到:

def flatten(l):
    result = []
    for element in l:
        if hasattr(element, "__iter__") and not isinstance(element, str):
            result.extend(flatten(element))
        else:
            result.append(element)
    return result
0

使用正则表达式怎么样?

>>> import re
>>> l = [1, [3, 6], 9, [2, [1, 3]], [4, [1], 5], [6], 1, [[2]]]
>>> l2 = map(int,re.sub('[\[\]\s]','',str(l)).split(','))
>>> l2.sort()
>>> l2
[1, 1, 1, 1, 2, 2, 3, 3, 4, 5, 6, 6, 9]
>>> 
0

一个仅适用于 Python 2.*的解决方案是使用来自 compiler 包的 ast 模块(在 Python 3 中已经不再可用了)。这个方法非常适合这个特定的例子:

import compiler

a = [1, [3, 6], 9, [2, [1, 3]], [4, [1], 5], [6], 1, [[2]]]
print sorted(compiler.ast.flatten(a))
# [1, 1, 1, 1, 2, 2, 3, 3, 4, 5, 6, 6, 9]
2

你可以从funcy模块中找到一个叫flatten的函数。这个模块的地址是https://github.com/Suor/funcy

如果你的环境中已经安装了funcy模块,下面的代码应该可以正常运行:

from funcy import flatten

nlist = [1, [3, 6], 9, [2, [1, 3]], [4, [1], 5], [6], 1, [[2]]]
flat_list = flatten(nlist)

print(nlist)
# [1, [3, 6], 9, [2, [1, 3]], [4, [1], 5], [6], 1, [[2]]]

print(sorted(flat_list))
# [1, 1, 1, 1, 2, 2, 3, 3, 4, 5, 6, 6, 9]
3

你可以通过递归的方式把数据压平,像这样做

>>> def rec(current_item):
...     if type(current_item) == list:
...         for items in current_item:
...             for item in rec(items):
...                 yield item
...     elif type(current_item) == int:
...         yield current_item

然后可以像这样对它进行排序

>>> sorted(rec([1, [3, 6], 9, [2, [1, 3]], [4, [1], 5], [6], 1, [[2]]]))
[1, 1, 1, 1, 2, 2, 3, 3, 4, 5, 6, 6, 9]

撰写回答