简体   繁体   English

如何将带有子列表的列表转换为统一列表(扁平化)?

[英]How can I convert a list with sublist into a uniform list (flattening)?

I have a list of coordinates as following:我有一个坐标列表如下:

temp = [((20.0, 15.076858380630263), (20.0, 16.92468707613784)), (5.430012747754155, 3.3503228946034667), (7.364023506893538, 7.013767290971433), (11.932318028181742, 8.766709807679579), ((12.839934501779176, 11.300824688102473), (13.285114114146213, 14.10378570292717),(14.839934501779176, 16.300824688102473))]

As you can see there some nested lists with multiple coordinates, so I want it be look like the following:正如您所看到的,有一些具有多个坐标的嵌套列表,所以我希望它如下所示:

temp =[(20.0, 15.076858380630263), (20.0, 16.92468707613784), (5.430012747754155, 3.3503228946034667), (7.364023506893538, 7.013767290971433), (11.932318028181742, 8.766709807679579), (12.839934501779176, 11.300824688102473), (13.285114114146213, 14.10378570292717), (14.839934501779176, 16.300824688102473)]

This is just an example and I have a huge output and do not know where these nested listed located with how many coordinates inside it.这只是一个例子,我有一个巨大的输出,不知道这些嵌套列表位于哪里,里面有多少坐标。 But the overall structure is the same.但整体结构是一样的。

Thank you.谢谢你。

you can use a list comprehension:您可以使用列表理解:

[j  for i in temp for j in (i if isinstance(i[0], tuple) else [i])]

output:输出:

[(20.0, 15.076858380630263),
 (20.0, 16.92468707613784),
 (5.430012747754155, 3.3503228946034667),
 (7.364023506893538, 7.013767290971433),
 (11.932318028181742, 8.766709807679579),
 (12.839934501779176, 11.300824688102473),
 (13.285114114146213, 14.10378570292717),
 (14.839934501779176, 16.300824688102473)]

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

相关问题 如何将子列表转换为列表 - How to convert sublist to list 如何创建新的子列表列表? - How can i create a new list of sublist? 如何将列表列表转换为键为整数且值为 integer 所属的子列表的索引的字典? - How can I convert a list of lists to a dictionary whose keys are integers and values are the index of the sublist to which the integer belongs? 如何将字符串项作为子列表项追加到列表中? - How can I append a string item as a sublist item in a list? 如何在包含多个子列表的列表中检查多个条件? - How can I check several conditions on a list containing several sublist? 如果子列表中存在术语,如何将其仅追加到另一个列表? - How can I append a sublist only to another list if a term exists in it? 如何在适当的位置反转列表中的子列表? - How do I reverse a sublist in a list in place? 如果该子列表中的任何元素在另一个列表中,如何删除列表中的列表(即子列表)? - how to delete a list within a list (i.e., a sublist) if any element of that sublist is in another list? 如何删除嵌套列表中另一个子列表中的子列表? - How to remove a sublist in nested list that are in another sublist? 我们如何在子列表列表中枚举列表? - How can we enumerate list inside list of sublist?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM