
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
Sort by Uppercase Frequency in Python
When it is required to sort the elements of the list by frequency of uppercase elements, a method is defined that uses list comprehension and the ‘isupper’ method.
Below is a demonstration of the same −
Example
def higher_character_sort(sub): return len([ele for ele in sub if ele.isupper()]) my_list = ["pyt", "is", "FUN", "to", "Learn"] print("The list is:") print(my_list) my_list.sort(key=higher_character_sort) print("The result is:") print(my_list)
Output
The list is: ['pyt', 'is', 'FUN', 'to', 'Learn'] The result is: ['pyt', 'is', 'to', 'Learn', 'FUN']
Explanation
A method named ‘higher_character_sort’ is defined that tales an element as parameter.
A list comprehension is used to iterate over the elements and the ‘isupper’ method is used to check if the element is upper case letter or lower case letter.
The length of this output is returned as output.
Outside the method, a list of strings is defined and displayed on the console.
The list is sorted using the ‘sort’ method and the key is specified as the previously defined method.
This is displayed as output on the console.
Advertisements