Identify Consecutive Numbers in a List
The task is to divide a list into groups of consecutive numbers. Each group should include only consecutive numbers. The output must retain individual numbers and not combine them into ranges.
Solution:
In Python, you can use the built-in groupby function along with a custom key to achieve this:
from itertools import groupby from operator import itemgetter ranges = [] for key, group in groupby(enumerate(data), lambda (index, item): index - item): group = map(itemgetter(1), group) if len(group) > 1: ranges.append(xrange(group[0], group[-1])) else: ranges.append(group[0])
Explanation:
Sample Output:
data = [2, 3, 4, 5, 12, 13, 14, 15, 16, 17, 20] ranges = [xrange(2, 5), xrange(12, 17), 20]
The above is the detailed content of How to Identify and Group Consecutive Numbers in a Python List?. For more information, please follow other related articles on the PHP Chinese website!