【问题标题】:How to create list of lists from sublists with varying length如何从具有不同长度的子列表创建列表列表
【发布时间】:2020-03-16 10:46:51
【问题描述】:

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

【问题讨论】:

    标签: python python-3.x list-comprehension nested-loops sublist


    【解决方案1】:

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

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

    【讨论】:

    • 非常感谢!这正是我想要的。对我来说,考虑到我缺乏 Python 专业知识,这是最易读的解决方案。
    【解决方案2】:

    您可以将itertools.zip_longest 与解包一起使用,以帮助您通过子列表的完整长度提取列:

    from itertools import zip_longest
    
    temp_list = [[87.33372], [86.30815, 300.0], [96.31665, 300.0]]
    
    result = [list(filter(lambda x: x is not None, x)) for x in zip_longest(*temp_list)]
    # [[87.33372, 86.30815, 96.31665], [300.0, 300.0]]
    

    【讨论】:

    • 这个解决方案对我来说更高级一些,但是一旦我对列表理解更加熟悉,我会重新审视。谢谢!
    【解决方案3】:

    你已经有一个循环,你只需要第二个
    这不是世界上干净的代码,但它会做,你首先计算最大长度,基本上是返回列表的列表数量,创建一个返回列表(一个空列表的列表),然后附加每个项目需要时

    temp_list=[[87.33372], [86.30815, 300.0], [96.31665, 300.0]]
    max_length = max([len(i) for i in temp_list])
    returned_list = [[] for i in range(max_length)]
    for item in temp_list:
        for i in range(max_length):
            try:
                returned_list[i].append(item[i])
            except IndexError as ie:
                pass
    

    【讨论】:

      猜你喜欢
      • 2020-05-04
      • 2020-01-11
      • 2020-06-27
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多