python - 根据条件创建列表列表
问题描述
我有一个列表,其中包含一些数字,直到某个值,然后以某种方式重复相同的行为,但没有周期性。我需要从输入中创建代表这些组的列表列表。
输入:
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])
解决方案
如果输出为空或当前项小于最后一个子列表中的最后一项,您可以附加一个新的子列表:
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]]
推荐阅读
- c - 指向一个空结构
- overflow - 运行时错误:将无符号偏移量添加到 0x602000000390 溢出到 0x60200000038c
- python - 有人可以帮我吗,我尝试运行这个 git 但我遇到了这些错误
- react-native - FlatList 没有渲染它显示除 FlatList 之外的任何内容
- javascript - 如何在展开可折叠 div 时调用 API 并使用 AngularJS 用 API 响应填充其内容?
- laravel - 使用 json_decode 时为 foreach() 提供的参数无效
- c# - 使用带有 Pipedream SSE API 的 ServiceStack ServerEventsClient 时出现 404 未找到错误
- c++ - 使用自定义比较器定义映射,其中值数据结构也具有自定义比较器
- ruby-on-rails - 根据rails中另一个下拉列表的值生成下拉列表值
- json - 从 json api 角度获取对象中的对象不显示