
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
Group Strings by K Length Using Suffix in Python
When it is required to group strings by K length using a suffix, a simple iteration and the ‘try’ and ‘except’ blocks are used.
Example
Below is a demonstration of the same
my_list = ['peek', "leak", 'creek', "weak", "good", 'week', "wood", "sneek"] print("The list is :") print(my_list) K = 3 print("The value of K is ") print(K) my_result = {} for element in my_list: suff = element[-K : ] try: my_result[suff].append(element) except: my_result[suff] = [element] print("The resultant list is :") print(my_result)
Output
The list is : ['peek', 'leak', 'creek', 'weak', 'good', 'week', 'wood', 'sneek'] The value of K is 3 The resultant list is : {'ood': ['good', 'wood'], 'eak': ['leak', 'weak'], 'eek': ['peek', 'creek', 'week', 'sneek']}
Explanation
A list of strings is defined and is displayed on the console.
The value of ‘K’ is defined and is displayed on the console.
An empty dictionary is defined.
The list is iterated over.
The list is reversed and assigned to a variable.
The ‘try’ block is used to append the element to the dictionary.
The ‘except’ block assigns the element to the list’s specific index.
This list is the output that is displayed on the console.
Advertisements