Identifying Consecutive Number Groups in a List
When faced with the task of identifying groups of consecutive numbers within a list, there are multiple approaches to consider.
Inbuilt Python Functionality
Python provides a powerful tool for this task: the groupby() function. Utilizing this function, we can categorize elements based on the difference between their index and value. For instance, in the list [2, 3, 4, 5, 12, 13, 14, 15, 16, 17], the groupby() function would output the following groups:
[(2, [2, 3, 4, 5]), (12, [12, 13, 14, 15, 16, 17])]
Here, each group consists of elements whose index differs from their value by the same amount, indicating consecutive numbers.
Custom Function
An alternative approach involves creating a custom function. One implementation is given below:
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])
This function generates a list of tuples, where each tuple represents a consecutive number group. For the input [2, 3, 4, 5, 12, 13, 14, 15, 16, 17], the output would be:
[(2, 5), (12, 17), 20]
Note that individual numbers are returned as individual elements rather than ranges.
The above is the detailed content of How Can I Efficiently Identify Consecutive Number Groups in a Python List?. For more information, please follow other related articles on the PHP Chinese website!