在python列表中查找连续的整数

时间:2015-02-19 16:41:41

标签: python int range

我正在编写一个函数,它接受带有排序整数的列表,并返回一个包含任何找到的整数范围的字符串。例如:

my_list = [1,2,3,4,5,10,12,13,14,15]

find_range(my_list)  -> "1-5, 10, 12, 13-15"

到目前为止我写的这个功能很有用,但我认为它过于复杂......必须有一个更好,更pythonic的方法来完成这个。

我正在寻找有关如何解决此任务的任何反馈/意见。

def find_range(int_list):

   range_str = ''
   index_end = len(int_list)
   index_begin = 0

   while (index_begin < index_end):
       val_save = int_list[index_begin]
       index_next = index_begin + 1

       if index_next == index_end:
           if str(val_save) in range_str:
               break
           else:
               range_str += str(val_save)
               break

       value_begin, value_next = int_list[index_begin], int_list[index_next]

       while (value_next == value_begin + 1 and index_next + 1 < index_end):
           index_begin += 1
           index_next += 1
           value_begin, value_next = int_list[index_begin], int_list[index_next]

       index_begin += 1

       if index_begin + 1 == index_end:
           if int(int_list[index_begin]) == (1 + value_begin):
               value_begin +=1

       if val_save != value_begin:
           range_str += str(val_save) + "-" + str(value_begin) + " , "
       else:
           range_str += str(value_begin) + " , "

   return range_str

提前感谢您的反馈/意见。

1 个答案:

答案 0 :(得分:2)

来自the docs

from operator import itemgetter
from itertools import groupby
def contiguous_ints(lst): 
    ranges = [] 
    # Loop through the list of ints, and break it into lists of contiguous ints
    for k, g in grouby(enumerate(lst), lambda (i, x): i-x): 
        ranges.append(map(itemgetter(1), g) 
    # Print the first and last values of each list of contiguous ints
    for i in ranges:       
        print("%s-%s" % (i[0], i[-1]))

修改了一些格式。

相关问题