首页 > 解决方案 > python:展平列表列表的列表

问题描述

我知道以前有人问过这个问题,但是当有类型列表时,我没有看到任何解决方案:

original_list = [[1,2], [3], [4,5,[6]]]

试过这个方法:

def flatten(list):

    """Given a list that contains elements and other lists, this
       will return a new list that has no sublists ("flattened")"""

    flat = [] # new empty list to populate with flattened list

    for sublist in list: # iterate through list elements
        for element in sublist: #
            flat.append(element)

    return flat

print(flatten([1,2,3]))

这个方法也是:

old_list = [[1,2], [3], [4,5,[6]]]

flat1 = []

flat1 = [sum(old_list, [])] # 1 layer deep

flat2 = []

flat2 = [sum(flat1), []] # 2 layers deep

print(sort2)

没有任何运气...提示?谢谢!

标签: pythonlist

解决方案


这些方面的东西?

In [6]: original_list = [[1,2], [3], [4,5,[6]]]                                                                                                                         

In [7]: def flatten(potential_list): 
   ...:     new_list = [] 
   ...:     for e in potential_list: 
   ...:         if isinstance(e, list): 
   ...:             new_list.extend(flatten(e)) 
   ...:         else: 
   ...:             new_list.append(e) 
   ...:     return new_list 
   ...:                                                                                                                                                                 

In [8]: flatten(original_list)                                                                                                                                          
Out[8]: [1, 2, 3, 4, 5, 6]

推荐阅读