ภาพรวม
เรียงลำดับ element ใน list ตามความถี่ (frequency) จากมากไปน้อย ใช้ Counter.most_common()
ตัวอย่างโค้ด
from collections import Counter
my_list = [34, 56, 78, 99, 99, 99, 99, 99, 12, 12, 32, 51, 15, 11, 0, 0]
print("The list is:", my_list)
# Counter.most_common() คืน list of (element, count) เรียงจากมากไปน้อย
# ขยายกลับเป็น list ตามความถี่
my_result = [item for item, count in Counter(my_list).most_common() for _ in range(count)]
print("The result is:", my_result)
ผลลัพธ์
The list is: [34, 56, 78, 99, 99, 99, 99, 99, 12, 12, 32, 51, 15, 11, 0, 0]
The result is: [99, 99, 99, 99, 99, 0, 0, 12, 12, 32, 34, 11, 78, 15, 51, 56]
คำอธิบาย
- 99 ปรากฏ 5 ครั้ง -> อยู่หน้าสุด
- 0 และ 12 ปรากฏ 2 ครั้ง -> ตามมา (0 ก่อน 12 เพราะ most_common เรียงตามลำดับเจอ)
- ที่เหลือปรากฏ 1 ครั้ง -> ตามลำดับที่เจอใน list เดิม
วิธีเขียนอ่านง่ายกว่า
counter = Counter(my_list)
my_result = []
for item, count in counter.most_common():
my_result.extend([item] * count)
Pandas Alternative
import pandas as pd
s = pd.Series(my_list)
# value_counts() เรียงจากมากไปน้อย
result = []
for val, count in s.value_counts().items():
result.extend([val] * count)