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']]
- Python | Categorize tuple values into dictionary value list
- Find size of a list in Python
- Python | Subgroups of i'th index size in list
- Break a list into chunks of size N in Python
- Python | Size Range Combinations in list
- Python | Sort list of lists by the size of sublists
- Python | Combinations of elements till size N in list
- Python | Increase list size by padding each element by N
- Python | Convert List of String List to String List
- Python | Size of string in memory
- Python | Convert mixed data types tuple list to string list
- Python | Convert list of string to list of list
- Python Program to convert List of Integer to List of String
- Python | Convert string List to Nested Character List
- Python | Convert list of string into sorted list of integer
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.