繁体   English   中英

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

[英]How to flatten a list of nested tuples in Python?

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

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

我想把它变成这个:

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

最恐怖的方式是什么?

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

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

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

>>> sample = [('a', 'b'), ('c', 'd'), (('e', 'f'), ('h', 'i'))]
>>> list(flatten(sample))
[('a', 'b'), ('c', 'd'), ('e', 'f'), ('h', 'i')]

单行,使用列表理解:

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)

收益率:

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

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

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

一行解决方案是使用itertools.chain

>>> l = [('a', 'b'), ('c', 'd'), (('e', 'f'), ('h', 'i'))]
>>> from itertools import chain
>>> [*chain.from_iterable(x if isinstance(x[0], tuple) else [x] for x in l)]
[('a', 'b'), ('c', 'd'), ('e', 'f'), ('h', 'i')]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM