
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Grouped Consecutive Range Indices of Elements in Python
When it is required to get the grouped consecutive range of indices of elements in a list, a defaultdict is created. A simple iteration, along with ‘groupby’ method, ‘len’ method, ‘list’ method and the ‘append’ methods are used.
Example
Below is a demonstration of the same −
from itertools import groupby from collections import defaultdict my_list = [63, 12, 84, 91, 52, 39, 25, 27, 20, 11, 0,9] print("The list is : " ) print(my_list) my_index = 0 my_result = defaultdict(list) for key, sub in groupby(my_list): element = len(list(sub)) my_result[key].append((my_index, my_index + element - 1)) my_index += element print("The resultant dictionary is : ") print(my_result)
Output
The list is : [63, 12, 84, 91, 52, 39, 25, 27, 20, 11, 0, 9] The resultant dictionary is : defaultdict(, {63: [(0, 0)], 12: [(1, 1)], 84: [(2, 2)], 91: [(3, 3)], 52: [(4, 4)], 39: [(5, 5)], 25: [(6, 6)], 27: [(7, 7)], 20: [(8, 8)], 11: [(9, 9)], 0: [(10, 10)], 9: [(11, 11)]})
Explanation
The required packages are imported into the environment.
A list of integers is defined and is displayed on the console.
A value is initialized to 0.
A default dictionary is created.
The list is iterated over by applying the ‘groupby’ method on it.
The initialized value is appended to the empty dictionary.
This is displayed as the output on the console.
Advertisements