如何在Python中展平嵌套元组列表? [英] How to flatten a list of nested tuples in Python?

查看:383
本文介绍了如何在Python中展平嵌套元组列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a list of tuples that looks like this:

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

我想把它变成这样:

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

最Python化的方法是什么?

What is the most Pythonic way to do this?

推荐答案

单行,使用列表理解:

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))也可以执行此操作(尽管看起来很笨拙)

this is artificially creating a list if the element is not a tuple of tuples, then flattening all does the job. To avoid creating a single element list [x], (x for _ in range(1)) can also do the job (although it appears clunky)

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

Limitation: doesn't handle more than 1 level of nesting. In which case, a more complex/recursive solution must be coded (check Martijn's answer).

这篇关于如何在Python中展平嵌套元组列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆