对连续整数进行分组并允许1的间隙 [英] Group consecutive integers and tolerate gaps of 1

查看:46
本文介绍了对连续整数进行分组并允许1的间隙的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,给定一个已排序整数的列表,我将按连续的值 将它们分组,并允许间隙为1.

In Python, given a list of sorted integers, I would to group them by consecutive values and tolerate gaps of 1.

例如,给定一个列表my_list:

In [66]: my_list
Out[66]: [0, 1, 2, 3, 5, 6, 10, 11, 15, 16, 18, 19, 20]

我想要以下输出:

[[0, 1, 2, 3, 5, 6], [10, 11], [15, 16, 18, 19, 20]]

现在,如果我不必忍受1的缺口,我可以应用

Now, if I didn't have to tolerate gaps of 1, I could apply the neat solution explained here:

import itertools
import operator
results = []
for k, g in itertools.groupby(enumerate(my_list), lambda (i,x):i-x):
        group = map(operator.itemgetter(1), g)
        results.append(group)

是否可以将我的额外要求纳入上述解决方案中?如果没有,解决问题的最佳方法是什么?

Is there a way to incorporate my extra requirement in the above solution? If not, what's the best way to tackle the problem?

推荐答案

如有疑问,您可以随时编写自己的生成器:

When in doubt you can always write your own generator:

def group_runs(li,tolerance=2):
    out = []
    last = li[0]
    for x in li:
        if x-last > tolerance:
            yield out
            out = []
        out.append(x)
        last = x
    yield out

演示:

list(group_runs(my_list))
Out[48]: [[0, 1, 2, 3, 5, 6], [10, 11], [15, 16, 18, 19, 20]]

这篇关于对连续整数进行分组并允许1的间隙的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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