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

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

问题描述

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

  #I有:
full_list = [0,1,2,3,10,11,12,59]
#I想要:
continuous_integers = [[0,1,2,3 ],[10,11,12],[59]]

我有以下工作,但似乎是一个很糟糕的方式来做到这一点:

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

我看过其他问题,提示itertools.groupby是一种有效的方法,但我不熟悉该函数,而且我似乎在编写lambda函数来描述连续性。

问:是有一个更好的方法来做到这一点(可能与itertools.groupby?)

注意事项:full_list将有1到59个整数,将总是排序,整数将您可以使用以下配方:


解决方案

 来自操作员导入itemgetter $ b $来自itertools import groupby 
full_list = [0,1,2,3,10,11,12,59] $ b $对于k,g中group(枚举(full_list),lambda(i,x):ix)]
#[[0,1,2,3]),b cont = [map(itemgetter(1),g) ,[10,11,12],[59]]


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)

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.

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

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

解决方案

You can use the following recipe:

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天全站免登陆