如果运行时间不超过3,如何将其拆分为序列/运行/后续数字?
拥有如下数组
[1, 2, 3, 5, 9, 10, 16, 17, 18, 19]
我的预期输出将是以下数组:
[1, 2, 3]
[5]
[9, 10]
[16, 17, 18]
[19]
e.g。 [[1, 2, 3], [5], [9, 10], [16, 17, 18], [19]]
如果是长度为8的运行,例如[1, 2, 3, 4, 5, 6, 7, 8]
我想获得8 / 3 + 1 = 2
个列表:
[1, 2, 3]
[4, 5, 6]
[7, 8]
答案 0 :(得分:2)
如果您为当前列表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
答案 1 :(得分:1)
这是我使用numpy
的版本:
import numpy as np
from itertools import chain
def split_list(mylist):
"""Function to do the initial split"""
# calculate differences
d = np.diff(mylist)
# when the differences are not 1 save that location
# we need a +1 to get make up for the lost element
breaks = list(np.arange(len(mylist) - 1)[d != 1] + 1)
slices = zip([0] + breaks, breaks + [len(mylist)])
# slice up the list
int_list = [mylist[a:b] for a, b in slices]
# chop up long sequences
chopped = [chop(l) for l in int_list]
# flatten the list once
return list(chain.from_iterable(chopped))
def chop(sublist, max_len=3):
"""Chops a list into chunks of length max_len"""
breaks = list(range(0, len(sublist), max_len))
slices = zip(breaks, breaks[1:] + [len(sublist)])
return [sublist[a:b] for a, b in slices]
在给出的列表上运行此命令:
>>> split_list([1, 2, 3, 5, 9, 10, 16, 17, 18, 19])
[[1, 2, 3], [5], [9, 10], [16, 17, 18], [19]]
答案 2 :(得分:-1)
这样的东西?
def split_list(list, sub_list_size = 3):
sublists = []
for i in range(0, len(list), sub_list_size):
start = i
end = i + sub_list_size
sublists.append(list[start:end])
return sublists
# your list
mylist = [1,2,3,4,5,6,7,8, 9, 10, 11]
# your output
sublists = split_list(mylist)
print(sublists)
产生以下输出
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]]
语法list[start:end]
即使end
大于实际列表大小也会有效。
希望这有帮助