python 将数组拆分为运行/序列 - 最好是 numpy

标签 python arrays numpy

如果运行不超过 3,我如何将其拆分为序列/运行/后续数字?

有一个数组如下

[1, 2, 3, 5, 9, 10, 16, 17, 18, 19]

我的预期输出将是以下数组:

  1. [1,2,3]
  2. [5]
  3. [9, 10]
  4. [16,17,18]
  5. [19]

例如[[1,2,3],[5],[9,10],[16,17,18],[19]]

如果是长度为 8 的游程,例如[1, 2, 3, 4, 5, 6, 7, 8] 我想获得 8/3 + 1 = 2 列表:

  1. [1,2,3]
  2. [4,5,6]
  3. [7, 8]

最佳答案

如果您将当前列表命名为 x 并将新的输出列表命名为 new_list,您可以尝试(未经测试并假设原始列表中没有重复值)

k = 0
new_list = [[]]
for i in range(len(x) - 1):
    if x[i] not in new_list[max(k - 1, 0)]:
        new_list[k].append(x[i])
        for j in range(i + 1, len(x)):    
            if x[j] - x[i] == j - i and x[j] not in new_list[k]:
               new_list[k].append(x[j])
        k += 1
        new_list.append([])

new_list = [x for x in new_list if x != []] # gets rid of empty list at the end

关于python 将数组拆分为运行/序列 - 最好是 numpy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37791945/

相关文章:

java - 在Java中使用模式、匹配器

Python:快速循环np.array

python - 是否可以将数字放在 matplotlib 直方图之上?

python-3.x - 在 python 中使用 numpy 创建数学方程式

Python:如何快速堆叠数据框中某一列的所有数组?

python - 将字符串附加到 unicode 字符串列表

python - python的跨平台usb模块?

python - 我无法使用 cv2 的 VideoCapture 打开网络摄像头

php - 移除键后将其移向 0

多次将函数应用于对象的pythonic方式