如何将列表中的连续元素拆分为子列表 [英] How to split consecutive elements in a list into sublists
本文介绍了如何将列表中的连续元素拆分为子列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下列表:
indices_to_remove: [0,1,2,3,..,600,800,801,802,....,1200,1600,1601,1602,...,1800]
我基本上有3个连续索引的子集:
I have basically 3 subsets of consecutive indices:
- 0-600
- 800-1200
- 1600-1800
我想创建3个不同的小列表,这些小列表将仅包含连续的数字.
I would like to create 3 different small lists that will include only consecutive numbers.
预期结果:
indices_to_remove_1 : [0,1,2,3,....,600]
indices_to_remove_2 : [800,801,802,....,1200]
indices_to_remove_3 : [1600,1601,1602,....., 1800]
P.S:数字是任意和随机的;此外,我可能会遇到3个或更少的子集.
P.S: The numbers are arbitrary and random; moreover, I may encounter more than 3 subsets or less.
推荐答案
另一种方法是使用 more_itertools.consecutive_groups
:(以@Stephen的列表为例):
Another way is using more_itertools.consecutive_groups
:
(used @Stephen's list for an example):
import more_itertools as mit
for group in mit.consecutive_groups(indices_to_remove):
print(list(group))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90]
[160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170]
这篇关于如何将列表中的连续元素拆分为子列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文