展平列表而不删除元组

时间:2019-02-22 05:44:18

标签: python

如何在不删除元组的情况下展平包含元组的嵌套列表?  例如:

flatten([1,2,3,(4,5,6),[7,8,9]]) 
[1, 2, 3, (4, 5, 6),7,8,9]

3 个答案:

答案 0 :(得分:0)

def flatten(arr):
    if not isinstance(arr, list):
        return arr
    else:
        output = []
        for sy in arr:
            if isinstance(sy, list):
                temp = flatten(sy)
                for py in temp:
                    output.append(py)
            else:
                output.append(sy)
        return output

print (flatten([1,2,3,(4,5,6),[7,8,9]]))
#[1, 2, 3, (4, 5, 6), 7, 8, 9]

答案 1 :(得分:0)

尝试一下:

f = lambda *n: (e for a in n
    for e in (f(*a) if isinstance(a, (list)) else (a,)))

print(list(f([1,2,3,(4,5,6),[7,8,9]])))
# [1, 2, 3, (4, 5, 6), 7, 8, 9]

答案 2 :(得分:0)

为什么不是简单的循环:

>>> L = [1,2,3,(4,5,6),[7,8,9]]
>>> L2 = []
>>> for i in L:
    if isinstance(i,list):
        L2.extend(i)
    else:
        L2.append(i)


>>> L2
[1, 2, 3, (4, 5, 6), 7, 8, 9]
>>>