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
Python Categorize the given list by string size
Let's consider a list containing many strings of different lengths. In this article we will see how to club those elements into groups where the strings are of equal length in each group.
With for loop
We design a for loop which will iterate through every element of the list and happened it only to the list where its length matches with the length of existing element.
Example
listA = ['Monday','Thursday','Friday','Saturday','Sunday']
# Given list
print("Given list : \n",listA)
# Categorize by string size
len_comp = lambda x, y: len(x) == len(y)
res = []
for sub_list in listA:
ele = next((i for i in res if len_comp(sub_list, i[0])), [])
if ele == []:
res.append(ele)
ele.append(sub_list)
# Result
print("The list after creating categories : \n",res)
Output
Running the above code gives us the following result −
Given list : ['Monday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] The list after creating categories : [['Monday', 'Friday', 'Sunday'], ['Thursday', 'Saturday']]
With sort and groupby
In this approach we first shot all the elements as per their length and then apply the group by function which is part of itertools module.
Example
from itertools import groupby
listA = ['Monday','Thursday','Friday','Saturday','Sunday']
# Given list
print("Given list : \n",listA)
# Categorize by string size
get_len = lambda x: len(x)
sub_list = sorted(listA, key = get_len)
res = [list(ele) for i, ele in groupby(sub_list, get_len)]
# Result
print("The list after creating categories : \n",res)
Output
Running the above code gives us the following result −
Given list : ['Monday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] The list after creating categories : [['Monday', 'Friday', 'Sunday'], ['Thursday', 'Saturday']]
Advertisements