扁平嵌套元组 [英] Flatten Nested Tuples

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

问题描述

我有一个元组列表,其中一些是嵌套的:

I have a list of tuples, some of which are nested:

[(name,(6,9.0,2.4),link),(name,(7.8,9.0,5),link)...]

我想取消嵌套列表中每个项目的内部元组,但保留外部元组:

I would like to un-nest the inner tuple for each item in the list, but preserve the outer tuple:

[(name,6,9.0,2.4,link),(name,7.8,9.0,5,link)...]

这与所提出的问题的解决方案不同此处,解决方案试图保留其中的对.

This is different from the solution to the question posed here in which the solution sought to preserve the pairs.

推荐答案

给出

lst = [('xyz',(6,9.0,2.4),'link1'),('abc',(7.8,9.0,5),'link2')]

遍历 lst 解压缩从内部元组到外部元组.您可以通过列表理解来做到这一点.

Iterate over lst and unpack the inner tuples into the outer tuples. You can do this with a list comprehension.

>>> [(x, *y, z) for x, y, z in lst]
[('xyz', 6, 9.0, 2.4, 'link1'), ('abc', 7.8, 9.0, 5, 'link2')]

适用于python3.6.对于旧版本,请使用元组串联:

Works on python3.6. For older versions, use tuple concatenation:

>>> [(x,) + y + (z,) for x, y, z in lst]
[('xyz', 6, 9.0, 2.4, 'link1'), ('abc', 7.8, 9.0, 5, 'link2')]

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

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