
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 Program to Group Strings by K length Using Suffix
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