猛跑小猪
more_itertools.consecutive_groups是在4.0版中添加的。演示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]这个来源实现模拟经典配方(如@Nadia Alramli所示)。注:more_itertools第三方包是否可通过pip install more_itertools.
UYOU
“天真”的解决方案,我觉得至少有点可读性。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)]