Python3 中实现flattten函数

本文介绍了一种在Python3中手动实现多维数组到一维数组转换的方法,并提供了详细的代码示例及解释。
最近岁数据集进行处理的时候需要把多维数据转换为一维的,但是Python3中
已经不支持flatten函数了,所以自己写了一个把多维数组转换为一维数组的函数。

废话少说,代码如下:

@requires_authorization
# -*- coding:utf-8 -*-
def flatten(input_list):
    output_list = []
    while True:
        if input_list == []:
            break
        for index, value in enumerate(input_list):
            # index :索引序列  value:索引序列对应的值
            # enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,
            # 同时列出数据和数据下标,一般用在 for 循环当中。
            if type(value)== list:
                input_list = value + input_list[index+1:]
                break   # 这里跳出for循环后,从While循环进入的时候index是更新后的input_list新开始算的。
            else:
                output_list.append(value)
                input_list.pop(index)
                break
    return output_list

t=[1,[5,7,8],[2,7,8],"Hello",['You','are','the','only','one'],[[5,7,8],[2,7,8],[0,8,7]]]
print flatten(t)
# output   [1, 5, 7, 8, 2, 7, 8, 'Hello', 'You', 'are', 'the', 'only', 'one', 5, 7, 8, 2, 7, 8, 0, 8, 7]

代码中注意的小知识

#Attention 1 在enumerate中,index和value的对应情况
# 0 1
# 1 [5, 7, 8]
# 2 [2, 7, 8]
# 3 Hello
# 4 ['You', 'are', 'the', 'only', 'one']
# 5 [[5, 7, 8], [2, 7, 8], [0, 8, 7]]

# Attention 2
# [[[5, 7, 8],
#     [2, 7, 8],
#     [0, 8, 7]]]
# 当input_list变为如上所示的列表时,
# input_list = value + input_list[index+1:]  中input_list[index+1:] 为空

这些都可以在pycharm中通过断点调试得到印证。今天的学习就到这里啦

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值