Python | Group elements on break positions in list
Last Updated :
20 Feb, 2023
Many times we have problems involving and revolving around Python grouping. Sometimes, we might have a specific problem in which we require to split and group N element list on missing elements. Let’s discuss a way in which this task can be performed. Method : Using itemgetter() + map() + lambda() + groupby() This task can be performed using the combination of above functions in which we can group the elements in breaks calculated using lambda function by finding difference between the index and value in list. The map() is used to combine the logic and itemgetter ensures the grouping is on value. Works with Python2 only.
Python
from itertools import groupby
from operator import itemgetter
test_list = [ 1 , 2 , 4 , 5 , 6 , 8 , 9 , 11 ]
print ("The original list is : " + str (test_list))
res = list ( map (itemgetter( 1 ), j) for i, j in
groupby( enumerate (test_list), lambda (x, y) : x - y))
print ("Grouping of elements at breaks : " + str (res))
|
Output :
The original list is : [1, 2, 4, 5, 6, 8, 9, 11]
Grouping of elements at breaks : [[1, 2], [4, 5, 6], [8, 9], [11]]
Time Complexity: O(n)
Auxiliary Space: O(n)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...