首页 > 解决方案 > 从python中的列表中创建降序值的子列表

问题描述

我是编程新手。我开始做这个问题,我必须从给定列表中创建降序值的子列表。

input_list=[7,1,6, 17, 18, 25, 25, 21, 11, 5 ,3 ,3,26,25]

预期的输出应该是:

descend_lists=[[7, 1], [25, 25, 21, 11, 5, 3, 3], [26, 25]]

我不知道从哪里开始。我的想法是,如果元素大于元素,我将ithith+1元素一起检查,然后将两个元素添加到. 请帮帮我。ithith+1descend_list

标签: pythonlist

解决方案


我的做法是遍历原始列表,考虑到一个临时列表,该列表由当前降序的子列表组成,并在它停止降序时弹出它。

def sublists(l):
    result = [] # the list of sub-lists
    sublist = [] # temporary sub-list kept in descending order
    for i in range(len(l)):
        sublist.append(l[i]) # add the element
        if(i == len(l) - 1 or l[i] < l[i+1]):
            result.append(sublist)
            sublist = []
    return result

在 if 语句中,发生的情况是当您到达列表末尾 (i == len(l) - 1) 或到达降序末尾 (l[i] < l [i+1])。请注意,您需要编写i == len(l) - 1 or l[i] < l[i+1]l[i] < l[i+1] or i == len(l) - 1否则您会收到 OutOfBounds 错误(l[i+1]此时访问是非法的。)

这将保留列表中的所有元素并为排序列表(具有不同元素)生成所有单例,而不是简单地将它们丢弃。这一点,以及我相信这种形式的代码更适合初学者阅读这一事实,这就是为什么我在这里添加我的答案而不是@Ch3steR 的答案


推荐阅读