-
繁星淼淼
如果您被允许使用外部包,则more_itertools具有split_when方法,它可以满足您的需求:import more_itertoolslst = [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]]
-
沧海一幻觉
我只是检查两个数字之间的差是否大于 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 restests = ([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]]
-
慕桂英3389331
numpy使用:运行速度非常快且简短的解决方案(一旦使用安装numpy python -m pip install numpy)。在线尝试一下!import numpy as npfor 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])]