根据序列中的缺失数字拆分列表

发布于 2021-01-29 19:34:14

我正在寻找一种最有效的方法,根据序列中缺少的数字将数字列表分成较小的列表。例如,如果初始列表为:

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]]
关注者
0
被浏览
69
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    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模块中的函数都会生成中断。诀窍在于,返回值是列表中的数字减去列表中元素的位置。当数字中有空格时,此差异会更改。

    itemgetter功能来自operator模块,您必须导入该模块和itertools模块,此示例才能正常工作。

    另外,作为列表理解:

    >>> [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]]
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看