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

标签 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

预先感谢您的反馈/评论。

最佳答案

来自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]))

修复了一些格式。

关于python - 在python列表中查找连续整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28611905/

相关文章:

python - 使用 beautifulsoup 获取跨度标题

python - 导入库时出现延迟的原因是什么?

python - 使列表的元组包括按字母顺序排列的数字、字母、计数

c - 有什么理由在 64 位 CPU 上使用 32 位整数进行常见操作?

python - 计算某个值在列表中出现的次数

excel - 如何对 Applescript 范围引用对象进行操作以确定行数?

python - 如何检查列表中的字符串然后选择该项目的其余部分,

java - 在数组索引处打印值返回哈希码

Mysql:获取所选时间之间的小时数

JavaScript 多语句