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

Python - Tần suất phần tử trong phạm vi phần trăm

Khi cần tìm tần suất phần tử trong phạm vi phần trăm, dùng Counter kết hợp lặp đơn giản.

Ví dụ

from collections import Counter

my_list = [56, 34, 78, 90, 11, 23, 6, 56, 79, 90]
print("The list is:")
print(my_list)

start, end = 13, 60
my_freq = dict(Counter(my_list))
my_result = []

for element in set(my_list):
    percent = (my_freq[element] / len(my_list)) * 100
    if percent >= start and percent <= end:
        my_result.append(element)

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

Đầu ra

The list is: [56, 34, 78, 90, 11, 23, 6, 56, 79, 90]
The result is: [56, 90]

Giải thích

  • Nhập Counter.
  • Định nghĩa list, start, end.
  • Tạo dictionary tần suất từ Counter.
  • Lặp set(list), tính phần trăm, nếu trong khoảng [start, end] thì thêm vào kết quả.
  • Hiển thị.