如何卸载混合类型的元组?

2024-04-16 06:58:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将混合类型的元组展平到一个列表中。以下功能不会产生所需的输出:

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']]

输出应为:

^{pr2}$

Tags: 功能类型列表lenreturnifisdef
2条回答
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']

相关问题 更多 >