Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
441 views
in Technique[技术] by (71.8m points)

lambda - python return lists of continuous integers from list

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...