Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Python - Đếm tần suất độ dài hàng ma trận

Khi cần đếm tần suất độ dài hàng ma trận, ta lặp qua và cộng tần suất vào dictionary rỗng hoặc tăng nếu tìm thấy lại.

Ví dụ

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)

Đầu ra

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

Giải thích

  • Định nghĩa list, hiển thị.
  • Dictionary rỗng.
  • Lặp list, nếu độ dài chưa có thì gán 1, ngược lại tăng 1.
  • Hiển thị kết quả.