如何在Python中展平嵌套元组列表?

Dav*_*Liu 4 python list-comprehension flatten

我有一个看起来像这样的元组列表:

[('a', 'b'), ('c', 'd'), (('e', 'f'), ('h', 'i'))]
Run Code Online (Sandbox Code Playgroud)

我想把它变成这个:

[('a', 'b'), ('c', 'd'), ('e', 'f'), ('h', 'i')]
Run Code Online (Sandbox Code Playgroud)

最恐怖的方式是什么?

Jea*_*bre 6

一行,使用列表理解:

l = [('a', 'b'), ('c', 'd'), (('e', 'f'), ('h', 'i'))]

result = [z for y in (x if isinstance(x[0],tuple) else [x] for x in l) for z in y]

print(result)
Run Code Online (Sandbox Code Playgroud)

产量:

[('a', 'b'), ('c', 'd'), ('e', 'f'), ('h', 'i')]
Run Code Online (Sandbox Code Playgroud)

如果元素不是元组的元组,这是人为地创建一个列表,然后展平所有的工作。为避免创建单个元素列表[x](x for _ in range(1))也可以完成这项工作(虽然看起来笨重)

限制:不能处理超过 1 级的嵌套。在这种情况下,必须编写更复杂/递归的解决方案(检查Martijn 的答案)。


Mar*_*ers 5

规范的非展平配方调整为仅在值中有元组时不展平:

def flatten(l):
    for el in l:
        if isinstance(el, tuple) and any(isinstance(sub, tuple) for sub in el):
            for sub in flatten(el):
                yield sub
        else:
            yield el
Run Code Online (Sandbox Code Playgroud)

这只会解包元组,并且只有在其中有其他元组时:

>>> sample = [('a', 'b'), ('c', 'd'), (('e', 'f'), ('h', 'i'))]
>>> list(flatten(sample))
[('a', 'b'), ('c', 'd'), ('e', 'f'), ('h', 'i')]
Run Code Online (Sandbox Code Playgroud)