Flatten Nested Tuples

无人久伴 提交于 2020-01-30 07:32:29

问题


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.


回答1:


Given

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

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')]

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')]


来源:https://stackoverflow.com/questions/52573594/flatten-nested-tuples

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!