Python | 列表的扁平化处理

2022/4/29 1:12:43

本文主要是介绍Python | 列表的扁平化处理,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

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

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

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函数

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]

 

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

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

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] 

 

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

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

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]

 



这篇关于Python | 列表的扁平化处理的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程