开发者社区> 问答> 正文

如何从具有不同长度的子列表中创建列表列表

我是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]...]

问题来源:stackoverflow

展开
收起
is大龙 2020-03-23 17:38:58 454 0
1 条回答
写回答
取消 提交回答
  • 我将建议与奥斯汀相同的答案,但我建议使用最干净的答案,作为更冗长的替代方法,它应该可以轻松说明代码中发生的事情,您可以使用以下代码。

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

    回答来源:stackoverflow

    2020-03-23 17:39:05
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载