在python中创建降序值的子列表

2024-07-05 14:45:45 发布

您现在位置: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元素,如果ith元素大于ith+1元素,然后将这两个元素添加到descend_list。请帮帮我。你知道吗


Tags: 元素列表input编程listslist新手降序
2条回答

您可以通过迭代input_list并检查ith元素是否大于ith+1元素来实现这一点。如果上述条件为真,则将ith元素附加到saytemp列表。一旦这个条件失败,将ith+1添加到temp列表为什么,因为例如,如果list=[7,6,5,8]根据我们的逻辑,我们将7添加到temp列表和6。但是当我们在5时,条件就失败了。但是我们还要添加5以获得所需的输出。现在将temp列表附加到descend_lists。你知道吗

代码:

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

def split1(X:list)->list:
    new_list=[]                    #intermediate list
    final=[]                       #final will contain the answer you wanted
    for idx in range(0,len(X)-1):
        if(X[idx]>=X[idx+1]):
            new_list.append(X[idx])
        else:
            if new_list !=[]:               # you come into else only X[i]< X[i+1]
                new_list.append(X[idx])     # that implies x[i] should be in new_list so i added x[idx] again
                final.append(new_list)      # now add the whole new_list to final
                new_list=[]                 # Now flush the values in new_list

    new_list.append(X[-1])                  # I ran my for loop len(X)-1 times so the last element needs to be added
    final.append(new_list)                  
    return final                            # The answer you wanted
print(split1(numbers))

输出:

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

If the list is sorted i.e list=[1,2,3,4] then output would be [[4]] and it makes sense because it's the only element where our condition is true.

希望这对你有帮助。你知道吗

我要做的是迭代原始列表,考虑由降序的当前子列表组成的临时列表,并在它停止降序时弹出它。你知道吗

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,否则会出现边界外错误(此时访问l[i+1]是非法的)

这将保留列表中的所有元素,并为已排序的列表(具有不同元素)生成所有单例,而不是简单地将它们丢弃。这就是为什么我在这里添加了我的答案,而不是@Ch3steR的答案

相关问题 更多 >