python - 从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]]
我不知道从哪里开始。我的想法是,如果元素大于元素,我将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 的答案
推荐阅读
- ruby - 为什么我从 Firebase 动态链接 API 收到服务器错误?
- sql-server - 在 SQL Server 中查询公共角色的登录名会返回意外结果
- php - 键'PRIMARY'的重复条目'19'插入php mysql
- forms - 在symfony 2中将参数传递给formType
- sql - 您可以从 BigQuery 中的选择语句中指定非空列约束吗?
- php - PHP:针对数据库表的文本区域输入验证
- python - 从一个列表中删除一个项目并将其存储到另一个列表的末尾
- java - 存在外键约束时如何从 MySQL 表中删除一行?
- html - Bootrap 4.1.1 横幅图像和导航栏不是全宽
- c# - 插入记录的 ID