关于python:如何取消混合类型的元组?

How do I unnest a tuple with mixed types?

本问题已经有最佳答案,请猛点这里访问。

我想把一个混合类型的元组展平到一个列表中。以下功能不产生所需的输出:

1
2
3
4
5
6
7
8
9
10
a = (1, 2, 3, ['first', 'second'])
def flatten(l):
return flatten(l[0]) + (flatten(l[1:]) if len(l) > 1 else []) if type(l) is list else [l]

>>> flatten(a)
[(1, 2, 3, ['first', 'second'])]
>>> flatten(flatten(a))
[(1, 2, 3, ['first', 'second'])]
>>> [flatten(item) for item in a]
[[1], [2], [3], ['first', 'second']]

输出应为:

1
>>> [1, 2, 3, 'first', 'second']


1
2
3
4
5
6
7
8
9
10
11
12
def flatten(l):
    if isinstance(l, (list,tuple)):
        if len(l) > 1:
            return [l[0]] + flatten(l[1:])
        else:
            return l[0]
    else:
        return [l]

a = (1, 2, 3, ['first', 'second'])

print(flatten(a))

[1, 2, 3, 'first', 'second']