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
Selected Reading
Python - Count the frequency of matrix row length
When working with matrices (lists of lists), you may need to count how many rows have the same length. Python provides several approaches to count the frequency of matrix row lengths using dictionaries or the Counter class.
Using Dictionary with Manual Counting
The traditional approach iterates through the matrix and manually tracks row length frequencies ?
matrix = [[42, 24, 11], [67, 18], [20], [54, 10, 25], [45, 99]]
print("The matrix is:")
print(matrix)
frequency = {}
for row in matrix:
length = len(row)
if length not in frequency:
frequency[length] = 1
else:
frequency[length] += 1
print("Row length frequency:")
print(frequency)
The matrix is:
[[42, 24, 11], [67, 18], [20], [54, 10, 25], [45, 99]]
Row length frequency:
{3: 2, 2: 2, 1: 1}
Using Counter from collections
The Counter class provides a more concise solution for counting frequencies ?
from collections import Counter
matrix = [[42, 24, 11], [67, 18], [20], [54, 10, 25], [45, 99]]
# Count frequencies of row lengths
row_lengths = [len(row) for row in matrix]
frequency = Counter(row_lengths)
print("Row length frequency:")
print(dict(frequency))
Row length frequency:
{3: 2, 2: 2, 1: 1}
Using Dictionary get() Method
The get() method simplifies the counting logic by providing a default value ?
matrix = [[1, 2, 3, 4], [5, 6], [7], [8, 9, 10], [11, 12]]
frequency = {}
for row in matrix:
length = len(row)
frequency[length] = frequency.get(length, 0) + 1
print("Row length frequency:")
for length, count in sorted(frequency.items()):
print(f"Length {length}: {count} rows")
Row length frequency: Length 1: 1 rows Length 2: 2 rows Length 4: 2 rows
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| Manual Dictionary | Moderate | Good | Learning purposes |
| Counter | High | Best | Production code |
| get() Method | Good | Good | Simple counting tasks |
Conclusion
Use Counter from collections for the most readable and efficient solution. The manual dictionary approach helps understand the underlying logic, while get() method offers a clean middle ground.
Advertisements
