基于序列中缺失数字的Python拆分列表 [英] Python splitting list based on missing numbers in a sequence

查看:75
本文介绍了基于序列中缺失数字的Python拆分列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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文档:

>>> # 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.
>>> 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):
...     print map(itemgetter(1), g)
...
[1]
[4, 5, 6]
[10]
[15, 16, 17, 18]
[22]
[25, 26, 27, 28]

每次键函数更改其返回值时,itertools模块中的groupby()函数都会生成一个中断.诀窍是返回值是列表中的数字减去元素在列表中的位置.当数字之间存在差距时,这种差异就会改变.

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.

有关数据的完整示例:

>>> from operator import itemgetter
>>> from itertools import *
>>> seq2 = [1, 2, 4, 5, 6, 8, 9, 10]
>>> list = []
>>> for k, g in groupby(enumerate(seq2), lambda (i,x):i-x):
...     list.append(map(itemgetter(1), g))
... 
>>> print list
[[1, 2], [4, 5, 6], [8, 9, 10]]

或作为列表理解:

>>> [map(itemgetter(1), g) for k, g in groupby(enumerate(seq2), lambda (i,x):i-x)]
[[1, 2], [4, 5, 6], [8, 9, 10]]

这篇关于基于序列中缺失数字的Python拆分列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆