将列表部分展平到给定级别

时间:2019-03-01 16:36:34

标签: python list nested

正如评论中指出的那样,this相关问题的大多数(如果不是全部)答案都无法用于以下列表:

select * from USER_PART_INDEXES where index_name='NAME_PARTTABLE';

此外,该列表可以嵌套得更深。如何部分展平到用户给定级别(默认为无穷大)

ls = [1,2,[3,4]]

ls2 = [1,[2,3],[4,[5,6]]] 的所需输出:

展平至第1级:

ls2

展平至2级(或更高)

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

2 个答案:

答案 0 :(得分:1)

您可以递归地做到这一点:

def flatten(l, level=None):
    if level == 0:
        return l
    flattened = []
    for item in l:
        if isinstance(item, list):
            flattened.extend(flatten(item, level-1 if level is not None else None))
        else:
            flattened.append(item)

    return flattened

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

print(flatten(ls2, level=1))
# [1, 2, 3, 4, [5, 6]]

print(flatten(ls2, level=2))
# [1, 2, 3, 4, 5, 6]

print(flatten(ls2))
# [1, 2, 3, 4, 5, 6]

答案 1 :(得分:0)

一种方法

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

def make_list_of_list(a):
    return [[i]if not isinstance(i, list) else i for i in a]

def flatten(l):
    return [item for sublist in make_list_of_list(l) for item in sublist]

flatten(ls2) will result in [1, 2, 3, 4, [5, 6]]
flatten(flatten(ls2)) will result in [1, 2, 3, 4, 5, 6]