关于python:在不删除元组的情况下展平列表

Flattening lists without removing the tuples

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

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


为什么不简单的循环:

1
2
3
4
5
6
7
8
9
10
11
12
>>> 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]
>>>


尝试一下:

1
2
3
4
5
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]


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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]