我希望有一个列表列表,其中包含连续的数字序列
我有一个整数排序列表,喜欢这个
[1,2,3,4,6,7,9,10,12,13,14,17,18,19,21]
我似乎无法为此找到合适的算法(查找DP,但这与我的情况不符)
我想要这样的输出
[ [1,2,3,4], [6,7], [9,10], [12,13,14], [17,18,19] , [21]
答案 0 :(得分:4)
为获得更好的性能,您可能需要尝试使用numpy。首先使用np.diff
获得第一个差异大于1
的索引,然后使用np.split
将它们用于将数组分成几个块:
import numpy as np
a = np.array([1,2,3,4,6,7,9,10,12,13,14,17,18,19,21])
np.split(a,np.flatnonzero(np.diff(a) > 1) + 1)
[array([1, 2, 3, 4]),
array([6, 7]),
array([ 9, 10]),
array([12, 13, 14]),
array([17, 18, 19]),
array([21])]
答案 1 :(得分:3)
这是一种实现方法:
nums = [1, 2, 3, 4, 6, 7, 9, 10, 12, 13, 14, 17, 18, 19, 21]
# Find sequence boundaries
splits = [i + 1 for i, (n1, n2) in enumerate(zip(nums, nums[1:])) if n1 + 1 != n2]
splits.insert(0, 0)
splits.append(len(nums))
# Make subsequences
seqs = [nums[s1:s2] for s1, s2 in zip(splits, splits[1:])]
print(seqs)
# [[1, 2, 3, 4], [6, 7], [9, 10], [12, 13, 14], [17, 18, 19], [21]]
或者,如果您希望使用更“传统”的循环:
nums = [1, 2, 3, 4, 6, 7, 9, 10, 12, 13, 14, 17, 18, 19, 21]
seqs = [[nums[0]]]
for n in nums[1:]:
if n != seqs[-1][-1] + 1:
seqs.append([n])
else:
seqs[-1].append(n)
print(seqs)
# [[1, 2, 3, 4], [6, 7], [9, 10], [12, 13, 14], [17, 18, 19], [21]]
答案 2 :(得分:2)
您可以使用此itertools recipe。它使用itertools.groupby
通过使用enumerate
获取范围差异来对连续运行进行分组,以便所有递增的数字出现在同一组中。
演示:
from operator import itemgetter
from itertools import groupby
data = [1,2,3,4,6,7,9,10,12,13,14,17,18,19,21]
result = [list(map(itemgetter(1), g)) for _, g in groupby(enumerate(data), lambda x: x[0] - x[1])]
print(result)
输出:
[[1, 2, 3, 4], [6, 7], [9, 10], [12, 13, 14], [17, 18, 19], [21]]
答案 3 :(得分:0)
它不如numpy高效,但是您可以使用functools中的reduce():
http://localhost:8080/static/dir/myfile.js