python从列表中返回连续整数的列表 [英] python return lists of continuous integers from list

查看:36
本文介绍了python从列表中返回连续整数的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个整数列表,我想生成一个包含所有连续整数列表的列表.

I have a list of integers, and I want to generate a list containing a list of all the continuous integers.

#I have:
full_list = [0,1,2,3,10,11,12,59]
#I want:
continuous_integers = [[0,1,2,3], [10,11,12], [59]]

我有以下可行的方法,但似乎是一种糟糕的方法:

I have the following which works, but seems like a poor way to do it:

sub_list = []
continuous_list = []
for x in full_list:
    if sub_list == []:
        sub_list.append(x)
    elif x-1 in sub_list:
        sub_list.append(x)
    else:
        continuous_list.append(sub_list)
        sub_list = [x]
continuous_list.append(sub_list)

我看到其他问题表明 itertools.groupby 是一种有效的方法,但我不熟悉该函数,而且我似乎在编写 lambda 函数来描述连续性质时遇到了麻烦.

I've seen other questions suggesting that itertools.groupby is an efficient way to do this, but I'm not familiar with that function and I seem to be having trouble with writing a lambda function to describe the continuous nature.

问题:有没有更好的方法来做到这一点(可能使用 itertools.groupby?)

Question: Is there a better way to be doing this (possibly with itertools.groupby?)

注意事项:full_list 将有 1 到 59 个整数,将始终排序,整数将在 0 到 59 之间.

Considerations: full_list will have between 1 and 59 integers, will always be sorted, and integers will be between 0 and 59.

推荐答案

您可以使用以下配方:

from operator import itemgetter
from itertools import groupby
full_list = [0,1,2,3,10,11,12,59]
cont = [map(itemgetter(1), g) for k, g in groupby(enumerate(full_list), lambda (i,x):i-x)]
# [[0, 1, 2, 3], [10, 11, 12], [59]]

这篇关于python从列表中返回连续整数的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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