標識列表中的連續(xù)數(shù)字組我想在一個列表中識別一組連續(xù)的數(shù)字,以便:myfunc([2, 3, 4, 5, 12, 13, 14, 15, 16, 17, 20])返回:[(2,5), (12,17), 20]我想知道做這件事的最好方法是什么(尤其是在Python中內(nèi)置了一些東西的時候)。編輯:我最初忘記提到,單個數(shù)字應(yīng)該作為單個數(shù)字返回,而不是范圍。
3 回答

猛跑小豬
TA貢獻1858條經(jīng)驗 獲得超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條經(jīng)驗 獲得超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
提交
取消