识别列表中的连续数字组 [英] Identify groups of continuous numbers in a list
问题描述
我想识别列表中的连续数字组,以便:
I'd like to identify groups of continuous numbers in a list, so that:
myfunc([2, 3, 4, 5, 12, 13, 14, 15, 16, 17, 20])
返回:
[(2,5), (12,17), 20]
并且想知道实现此目的的最佳方法是什么(特别是如果Python内置了某些东西).
And was wondering what the best way to do this was (particularly if there's something inbuilt into Python).
请注意,我最初忘记提及应该将单个数字作为单个数字而不是范围返回.
Note I originally forgot to mention that individual numbers should be returned as individual numbers, not ranges.
推荐答案
more_itertools.consecutive_groups
was added in version 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]]
代码
应用此工具,我们将生成一个生成器函数,以查找连续数字的范围.
Applying this tool, we make a generator function that finds ranges of consecutive numbers.
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]
The source implementation emulates a classic recipe (as demonstrated by @Nadia Alramli).
注意:more_itertools
是可通过 pip install more_itertools
.
这篇关于识别列表中的连续数字组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!