gpt4 book ai didi

python - 从 python 列表中创建降序值的子列表

转载 作者:行者123 更新时间:2023-12-01 00:13:16 24 4
gpt4 key购买 nike

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

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

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

最佳答案

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

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 的答案

关于python - 从 python 列表中创建降序值的子列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59486303/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com