3 回答
TA贡献1775条经验 获得超11个赞
如果您被允许使用外部包,则more_itertools
具有split_when方法,它可以满足您的需求:
import more_itertools
lst = [1,2,3,4,5,6,8,9,10]
lst.sort()
splitted = list(more_itertools.split_when(lst, lambda x, y: abs(x-y) > 1))
print(splitted)
输出:
[[1, 2, 3, 4, 5, 6], [8, 9, 10]]
TA贡献1824条经验 获得超5个赞
我只是检查两个数字之间的差是否大于 1:
def mySplit(lst):
res = []
lst.sort()
subList = [lst[0]]
for i in range(1, len(lst)):
prev, cur = lst[i-1], lst[i]
if cur - prev > 1:
res.append(subList)
subList = []
subList.append(cur)
res.append(subList)
return res
tests = ([4,1,5,3], [4,2,1,3], [5,2,7,6,3,9], [1,2,3,4,5,6,8,9,10,13])
for test in tests:
print(mySplit(test))
出去:
[[1], [3, 4, 5]]
[[1, 2, 3, 4]]
[[2, 3], [5, 6, 7], [9]]
[[1, 2, 3, 4, 5, 6], [8, 9, 10], [13]]
TA贡献2036条经验 获得超8个赞
numpy
使用:运行速度非常快且简短的解决方案
(一旦使用安装numpy python -m pip install numpy
)。
import numpy as np
for l in [
[4,1,5,3],
[4,2,1,3],
[5,2,7,6,3,9],
[1,2,3,4,5,6,8,9,10],
]:
a = np.sort(l)
res = np.split(a, np.flatnonzero(np.abs(np.diff(a)) > 1) + 1)
print('input', l, 'sorted', a, '\n', 'result', res)
输出:
input [4, 1, 5, 3] sorted [1 3 4 5]
result [array([1]), array([3, 4, 5])]
input [4, 2, 1, 3] sorted [1 2 3 4]
result [array([1, 2, 3, 4])]
input [5, 2, 7, 6, 3, 9] sorted [2 3 5 6 7 9]
result [array([2, 3]), array([5, 6, 7]), array([9])]
input [1, 2, 3, 4, 5, 6, 8, 9, 10] sorted [ 1 2 3 4 5 6 8 9 10]
result [array([1, 2, 3, 4, 5, 6]), array([ 8, 9, 10])]
添加回答
举报