我正在寻找一种最有效的方法,根据序列中缺少的数字将数字列表分成较小的列表。例如,如果初始列表为:
seq1 = [1, 2, 3, 4, 6, 7, 8, 9, 10]
该函数将产生:
[[1, 2, 3, 4], [6, 7, 8, 9, 10]]
要么
seq2 = [1, 2, 4, 5, 6, 8, 9, 10]
会导致:
[[1, 2], [4, 5, 6], [8, 9, 10]]
旧Python文档中的Python 3版本代码:
>>> # Find runs of consecutive numbers using groupby. The key to the solution >>> # is differencing with a range so that consecutive numbers all appear in >>> # same group. >>> from itertools import groupby >>> from operator import itemgetter >>> data = [ 1, 4,5,6, 10, 15,16,17,18, 22, 25,26,27,28] >>> for k, g in groupby(enumerate(data), lambda i_x: i_x[0] - i_x[1]): ... print(list(map(itemgetter(1), g))) ... [1] [4, 5, 6] [10] [15, 16, 17, 18] [22] [25, 26, 27, 28]
groupby每当关键函数更改其返回值时,itertools模块中的函数都会生成中断。诀窍在于,返回值是列表中的数字减去列表中元素的位置。当数字中有空格时,此差异会更改。
groupby
该itemgetter功能来自operator模块,您必须导入该模块和itertools模块,此示例才能正常工作。
itemgetter
另外,作为列表理解:
>>> [map(itemgetter(1), g) for k, g in groupby(enumerate(seq2), lambda i_x: i_x[0] - i_x[1])] [[1, 2], [4, 5, 6], [8, 9, 10]]