Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python – Sort by Uppercase Frequency
Sorting strings by uppercase frequency means arranging them based on the count of capital letters they contain. This is useful for organizing text data by capitalization patterns. Python's sort() method with a custom key function makes this straightforward.
How It Works
The approach uses a custom function that counts uppercase letters in each string, then sorts the list using this count as the sorting key ?
def count_uppercase(text):
return len([char for char in text if char.isupper()])
words = ["pyt", "is", "FUN", "to", "Learn"]
print("Original list:")
print(words)
words.sort(key=count_uppercase)
print("Sorted by uppercase frequency:")
print(words)
Original list: ['pyt', 'is', 'FUN', 'to', 'Learn'] Sorted by uppercase frequency: ['pyt', 'is', 'to', 'Learn', 'FUN']
Using Lambda Function
You can make the code more concise using a lambda function instead of defining a separate function ?
words = ["Hello", "WORLD", "python", "Code", "AI"]
print("Original list:")
print(words)
words.sort(key=lambda x: sum(1 for char in x if char.isupper()))
print("Sorted by uppercase count:")
print(words)
Original list: ['Hello', 'WORLD', 'python', 'Code', 'AI'] Sorted by uppercase count: ['python', 'Hello', 'Code', 'AI', 'WORLD']
Sorting in Descending Order
To sort from highest to lowest uppercase frequency, use the reverse=True parameter ?
words = ["abc", "DEF", "GHi", "jkl", "MNO"]
def uppercase_count(text):
return sum(1 for char in text if char.isupper())
words.sort(key=uppercase_count, reverse=True)
print("Sorted by uppercase frequency (descending):")
print(words)
# Show the counts for clarity
for word in words:
count = uppercase_count(word)
print(f"'{word}' has {count} uppercase letters")
Sorted by uppercase frequency (descending): ['DEF', 'MNO', 'GHi', 'abc', 'jkl'] 'DEF' has 3 uppercase letters 'MNO' has 3 uppercase letters 'GHi' has 2 uppercase letters 'abc' has 0 uppercase letters 'jkl' has 0 uppercase letters
Key Points
The
isupper()method returnsTruefor uppercase charactersList comprehension efficiently counts uppercase letters
The
sort()method modifies the original list in-placeUse
sorted()if you want to keep the original list unchanged
Conclusion
Sorting by uppercase frequency is achieved using a custom key function that counts capital letters. This technique is useful for text processing and organizing strings by their capitalization patterns.
