Python - Count the frequency of matrix row length

PythonServer Side ProgrammingProgramming

When it is required to count the frequency of the matrix row length, it is iterated over and its frequency is added to the empty dictionary or incremented if found again.

Example

Below is a demonstration of the same

my_list = [[42, 24, 11], [67, 18], [20], [54, 10, 25], [45, 99]]

print("The list is :")
print(my_list)
my_result = dict()
for element in my_list:

   if len(element) not in my_result:
      my_result[len(element)] = 1

   else:
      my_result[len(element)] += 1

print("The result is :")
print(my_result)

Output

The list is :
[[42, 24, 11], [67, 18], [20], [54, 10, 25], [45, 99]]
The result is :
{1: 1, 2: 2, 3: 2}

Explanation

  • A list is defined and is displayed on the console.

  • An empty dictionary is defined.

  • The list is iterated over, and if the specific length is not present in the dictionary, the length in the dictionary is assigned to 1.

  • Otherwise, it is incremented by 1.

  • This is the output that is displayed on the console.

raja
Updated on 21-Sep-2021 07:58:38

Advertisements