最近岁数据集进行处理的时候需要把多维数据转换为一维的,但是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中通过断点调试得到印证。今天的学习就到这里啦


本文转载:CSDN博客