我正在编写一个函数,它接受一个包含排序整数的列表,并返回一个包含任何找到的整数范围的字符串。例如:
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/