python - 如何将列表中的连续元素拆分为子列表

标签 python arrays pandas list split

我有以下列表:

indices_to_remove: [0,1,2,3,..,600,800,801,802,....,1200,1600,1601,1602,...,1800]

我基本上有 3 个连续索引的子集:

  1. 0-600
  2. 800-1200
  3. 1600-1800

我想创建 3 个不同的小列表,其中只包含连续的数字。

预期结果:

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 个或更少的子集。

最佳答案

另一种方法是使用 more_itertools.consecutive_groups : (以@Stephen 的列表为例):

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]

关于python - 如何将列表中的连续元素拆分为子列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55914382/

相关文章:

python - 为什么我的多参数卡方会陷入错误循环?

python - 将 Flightradar24 API 转换为 pandas 数据帧

python - ndb.toplevel 会破坏交易吗?

javascript - 拆分方法然后连接

c++ - 在 main(...) 而不是全局中初始化类的静态常量数组成员?

python - 试图在两个字符串中找到匹配项 - Python

arrays - 将字符串数组保存到 CoreData

python - 在Python中循环子数据帧

python - 将连续出现的一定数量的数字从上到下均等地替换为某个值

python - 遍历数据框 Pandas 时如何获取列名?