Python中多层List展平为一层

转载https://www.cnblogs.com/wushaogui/p/9241931.html

1.定义减层方法

import functools 
import itertools 
import numpy 
import operator 
import perfplot 
from collections import Iterable  # or from collections.abc import Iterable 
from iteration_utilities import deepflatten 
 
#使用两次for循环 
def forfor(a): 
    return [item for sublist in a for item in sublist] 
 
#通过sum 
def sum_brackets(a): 
    return sum(a, []) 
 
#使用functools內建模块 
def functools_reduce(a): 
    return functools.reduce(operator.concat, a) 
 
#使用itertools內建模块 
def itertools_chain(a): 
    return list(itertools.chain.from_iterable(a)) 
 
#使用numpy 
def numpy_flat(a): 
    return list(numpy.array(a).flat) 
 
#使用numpy 
def numpy_concatenate(a): 
    return list(numpy.concatenate(a)) 
 
#自定义函数 
def flatten(items): 
    """Yield items from any nested iterable; see REF.""" 
    for x in items: 
        if isinstance(x, Iterable) and not isinstance(x, (str, bytes)): 
            yield from flatten(x) 
        else: 
            yield x 
 
def pylangs_flatten(a): 
    return list(flatten(a)) 
 
#使用库iteration_utilities 
def iteration_utilities_deepflatten(a): 
    return list(deepflatten(a, depth=1)) 

2.测试

a=[[1,2,3],[4,5,6],[7,8,9]] 
print(a) 
 
print('--------------------------') 
 
print(forfor(a)) 
print(sum_brackets(a)) 
print(functools_reduce(a)) 
print(itertools_chain(a)) 
print(numpy_flat(a)) 
print(numpy_concatenate(a)) 
print(pylangs_flatten(a)) 
print(iteration_utilities_deepflatten(a)) 

输出:

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
--------------------------
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值