Python | Categorize the given list by string size
Sometimes, we have a use case in which we need to perform the grouping of strings by various factors, like first letter or any other factor. These type of problems are typical to database queries and hence can occur in web development while programming. This article focuses on one such grouping by size of string. Let’s discuss certain ways in which this can be performed.
Method #1 : Using
next() + lambda + loop
The combination of above 3 functions is used to solve this particular problem by the naive method. The lambda function performs the task of finding like lengths, and next function helps in forward iteration.
The original list : ['man', 'a', 'geek', 'for', 'b', 'free'] The list after Categorization : [['man', 'for'], ['a', 'b'], ['geek', 'free']]
Method #2 : Using
sorted() + groupby()
This particular task can also be solved using the groupby function which offers a convenient method to solve this problem. The sorted function sorts the elements by size to be feed to groupby for the relevant grouping.
The original list : ['man', 'a', 'geek', 'for', 'b', 'free'] The list after Categorization : [['a', 'b'], ['man', 'for'], ['geek', 'free']]
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course