首页 > 解决方案 > 根据条件创建列表列表

问题描述

我有一个列表,其中包含一些数字,直到某个值,然后以某种方式重复相同的行为,但没有周期性。我需要从输入中创建代表这些组的列表列表。

输入:

index=[2,5,6,9,10,11,13,18,19,21, 3,5,8,9,12,17,119, 2,4,6,8,10,12,14,16,18,200, 3,5,7,9,11,14,15,19,233] 

期望输出

[[2, 5, 6, 9, 10, 11, 13, 18, 19, 21],
 [3, 5, 8, 9, 12, 17, 119],
 [2, 4, 6, 8, 10, 12, 14, 16, 18, 200],
 [3, 5, 7, 9, 11, 14, 15, 19, 233]]

我想出了这段代码,但起初我无法在没有明确干预的情况下将最后一次迭代转储到 list_of_lists 中。你能想出更好的方法吗?

temp_lst=[]
list_of_lists=[]
for i in range(len(index)-1):
    if index[i+1]>index[i]:
        temp_lst.append(index[i])

    else:
        temp_lst.append(index[i])        
        list_of_lists.append(temp_lst)
        temp_lst=[]

list_of_lists.append(temp_lst)
list_of_lists[-1].append(index[-1])

标签: pythonlistconditional-statements

解决方案


如果输出为空或当前项小于最后一个子列表中的最后一项,您可以附加一个新的子列表:

list_of_lists=[]
for i in index:
    if not list_of_lists or i < list_of_lists[-1][-1]:
        list_of_lists.append([])
    list_of_lists[-1].append(i)

list_of_lists变成:

[[2, 5, 6, 9, 10, 11, 13, 18, 19, 21],
 [3, 5, 8, 9, 12, 17, 119],
 [2, 4, 6, 8, 10, 12, 14, 16, 18, 200],
 [3, 5, 7, 9, 11, 14, 15, 19, 233]]

推荐阅读