Python | 列表的扁平化处理

一、使用sum()函数,可展开两层的嵌套列表

1
2
3
4
5
a = [[1, 2, 3], [ 4, 5, 6], [7], [8, 9]]
out = sum(a, [])
print(out)
 
output:[1, 2, 3, 4, 5, 6, 7, 8, 9]

 

二、使用itertools

1
2
3
4
5
6
7
import itertools
 
a = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
out = list(itertools.chain.from_iterable(a))
print(out)
 
output:[1, 2, 3, 4, 5, 6, 7, 8, 9]

 

三、使用operator、reduce函数

1
2
3
4
5
6
7
import operator
from functools import reduce
 
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(reduce(operator.add, a))
 
a:[1, 2, 3, 4, 5, 6, 7, 8, 9]

 

上面方法可能只对二层列表有效,如果无法确定嵌套深度,有如下的方法:

四、可以使用递归函数来解决(万能方式)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
data = [[[1],[2],[3]],[4,5],[[[[[[6]]]]]]]
print(data)
result = []
def take_out(arr):
    for item in arr:
        if isinstance(item,int):
            result.append(item)
        else:
            take_out(item)
take_out(data)
print(result)
 
out:[[[1], [2], [3]], [4, 5], [[[[[[6]]]]]]]
    [1, 2, 3, 4, 5, 6]

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
data = [[[1],[2],[3]],[4,5],[[[[[[6]]]]]]]
print(data)
result = []         #存放最终结果
def nested(lst):    #函数嵌套定义
    for item in lst:
        if isinstance(item, list):
            nested(item)        #递归子列表
        else:
            result.append(item) #扁平化列表
nested(data)
print(result)
 
 
[[[1], [2], [3]], [4, 5], [[[[[[6]]]]]]]
[1, 2, 3, 4, 5, 6]

  

 

五、使用标准库itertools中的chain()函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
from itertools import chain
from copy import deepcopy
 
data = [[[1],[2],[3]],[[4],[5],[6]]]
print(data)
result = deepcopy(data)
 
while True:
    result = list(chain(*result))
    if isinstance(result[0], int):
        break
print(result)
 
 
[[[1], [2], [3]], [[4], [5], [6]]]
[1, 2, 3, 4, 5, 6]

 

六、扩展库numpy

1
2
3
4
5
6
7
8
9
10
11
12
import numpy as np
 
data = [[[1],[2],[3]],[[4],[5],[6]]]
print(data)
 
temp_data = np.array(data)
a = list(temp_data.reshape(temp_data.size,))
print(a)
 
 
[[[1], [2], [3]], [[4], [5], [6]]]
[1, 2, 3, 4, 5, 6]

 

posted @   卷毛七号  阅读(918)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示