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']]
- Find size of a list in Python
- Break a list into chunks of size N in Python
- Python | Subgroups of i'th index size in list
- Python | Sort list of lists by the size of sublists
- Python | Size of string in memory
- Python | Convert list of string to list of list
- Python | Convert list of string into sorted list of integer
- Python | Convert list of numerical string to list of Integers
- Python | Convert string enclosed list to list
- Python | Convert a string representation of list into list
- Python | Check if given string can be formed by concatenating string elements of list
- Python | Check if string ends with any string in given list
- Sum of list (with string types) in Python
- Python | First Non-Empty String in list
- Python | Converting list string to dictionary
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.