标识列表中的连续数字组我想在一个列表中识别一组连续的数字,以便:myfunc([2, 3, 4, 5, 12, 13, 14, 15, 16, 17, 20])返回:[(2,5), (12,17), 20]我想知道做这件事的最好方法是什么(尤其是在Python中内置了一些东西的时候)。编辑:我最初忘记提到,单个数字应该作为单个数字返回,而不是范围。
3 回答
猛跑小猪
TA贡献1858条经验 获得超8个赞
more_itertools.consecutive_groups
演示
import more_itertools as mit iterable = [2, 3, 4, 5, 12, 13, 14, 15, 16, 17, 20][list(group) for group in mit.consecutive_groups(iterable)]# [[2, 3, 4, 5], [12, 13, 14, 15, 16, 17], [20]]
电码
def find_ranges(iterable): """Yield range of consecutive numbers.""" for group in mit.consecutive_groups(iterable): group = list(group) if len(group) == 1: yield group[0] else: yield group[0], group[-1]iterable = [2, 3, 4, 5, 12, 13, 14, 15, 16, 17, 20]list(find_ranges(iterable))# [(2, 5), (12, 17), 20]
more_itertools
pip install more_itertools
.
UYOU
TA贡献1878条经验 获得超4个赞
x = [2, 3, 4, 5, 12, 13, 14, 15, 16, 17, 22, 25, 26, 28, 51, 52, 57]def group(L): first = last = L[0] for n in L[1:]: if n - 1 == last: # Part of the group, bump the end last = n else: # Not part of the group, yield current group and start a new yield first, last first = last = n yield first, last # Yield the last group>>>print list(group(x))[(2, 5), (12, 17), (22, 22), (25, 26), (28, 28), (51, 52), (57, 57)]
添加回答
举报
0/150
提交
取消