如何在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).