首页 > 解决方案 > 如何从具有不同长度的子列表创建列表列表

问题描述

我是python的初学者,我有这个问题,我希望有人可以帮助我。

首先,我有一个不同长度的子列表列表

输入:

temp_list=[[87.33372], [86.30815, 300.0], [96.31665, 300.0]]

我正在尝试创建一个新的列表列表,其中子列表由每个列表子列表中相同索引的项目组成,我希望这听起来不会太复杂。

也许这会让它更清楚一点

所需的输出:

[[87.33372, 86.30815, 96.31665],[300.0, 300.0]]

我已经想到了这个公式,但我不确定如何实现它

x=0
new_list = [sublist[x][i],sublist[x+1][i]...]

标签: pythonpython-3.xlist-comprehensionnested-loopssublist

解决方案


我会推荐与奥斯汀相同的答案,我建议它是最干净的,但是作为更详细的替代方案,它应该很容易说明你可以使用以下代码中发生的事情。

temp_list = [[87.33372], [86.30815, 300.0], [96.31665, 300.0]]
new_list = []

#loop over each list
for items in temp_list:
    #for each item in the sublist get its index and value.
    for i, v in enumerate(items):
        #If the index is greater than the length of the new list add a new sublist
        if i >= len(new_list):
            new_list.append([])
        #Add the value at the index (column) position
        new_list[i].append(v)

print(new_list)

输出

[[87.33372, 86.30815, 96.31665], [300.0, 300.0]]

推荐阅读