Home > Backend Development > Python Tutorial > How to Identify and Group Consecutive Numbers in a Python List?

How to Identify and Group Consecutive Numbers in a Python List?

Susan Sarandon
Release: 2024-12-08 17:47:11
Original
682 people have browsed it

How to Identify and Group Consecutive Numbers in a Python List?

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])
Copy after login

Explanation:

  1. enumerate(data) creates a list of pairs, where each pair consists of an index (starting from 0) and the corresponding element in data.
  2. The lambda function (lambda (index, item): index - item) calculates the difference between the index and the element value. This difference serves as the key for grouping.
  3. groupby partitions the list of pairs into consecutive groups based on the key. Each group contains elements with the same difference.
  4. To retrieve the ranges of consecutive numbers, we map the pairs in each group to their second element (the actual number) using map(itemgetter(1), group).
  5. We check if each group contains more than one number. If so, we create a range for those numbers and append it to ranges. Otherwise, we simply add the number to ranges.

Sample Output:

data = [2, 3, 4, 5, 12, 13, 14, 15, 16, 17, 20]
ranges = [xrange(2, 5), xrange(12, 17), 20]
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template