根据序列中缺少的数字拆分列表 [英] Splitting list based on missing numbers in a sequence
问题描述
我正在寻找一种最有效的方法,根据序列中缺少的数字将数字列表拆分为较小的列表.例如,如果初始列表为:
I am looking for the most pythonic way of splitting a list of numbers into smaller lists based on a number missing in the sequence. For example, if the initial list was:
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 3版本的旧Python 文档:
Python 3 version of the code from the old Python documentation:
>>> # 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模块中的函数会生成一个中断.诀窍是返回值是列表中的数字减去元素在列表中的位置.当数字之间存在差距时,这种差异就会改变.
The groupby
function from the itertools module generates a break every time the key function changes its return value. The trick is that the return value is the number in the list minus the position of the element in the list. This difference changes when there is a gap in the numbers.
itemgetter
函数来自运算符模块,您必须导入此代码和itertools模块,此示例才能正常工作.
The itemgetter
function is from the operator module, you'll have to import this and the itertools module for this example to work.
或者,作为列表理解:
>>> [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]]
这篇关于根据序列中缺少的数字拆分列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!