Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การนับจำนวนครั้งที่ปรากฏของแต่ละตัวเลขในลิสต์ Python

มีลิสต์ตัวเลขซ้ำกัน ต้องการสร้าง sublist ที่เก็บ [ตัวเลข, จำนวนครั้งที่ปรากฏ] สำหรับทุกตัวเลขที่ไม่ซ้ำกัน

วิธีที่ 1: ใช้ for loop และ append (Manual)

เปรียบเทียบแต่ละคู่ นับจำนวน แล้วสร้าง sublist

ตัวอย่าง

def occurrences(list_in):
    listB = []
    list_uniq = []
    for i in range(len(list_in)):
        a = 0
        row = []
        if i not in listB:
            for j in range(len(list_in)):
                if list_in[i] == list_in[j]:
                    a += 1
            row.append(list_in[i])
            row.append(a)
            listB.append(row)
    for j in listB:
        if j not in list_uniq:
            list_uniq.append(j)
    return list_uniq

listA = [13, 65, 78, 13, 12, 13, 65]
print("Number of occurrences of each element in the list:\n")
print(occurrences(listA))

ผลลัพธ์

Number of occurrences of each element in the list:
[[13, 3], [65, 2], [78, 1], [12, 1]]

วิธีที่ 2: ใช้ collections.Counter (แนะนำ)

Counter นับความถี่อัตโนมัติ แล้วแปลงเป็นลิสต์ของ [key, value]

ตัวอย่าง

from collections import Counter

def occurrences(list_in):
    c = Counter(list_in)
    new_list = []
    for k, v in c.items():
        new_list.append([k, v])
    return new_list

listA = [13, 65, 78, 13, 12, 13, 65]
print("Number of occurrences of each element in the list:\n")
print(occurrences(listA))

ผลลัพธ์

Number of occurrences of each element in the list:
[[13, 3], [65, 2], [78, 1], [12, 1]]

ข้อดีของ Counter: โค้ดสั้น อ่านง่าย เร็ว (C implementation) และมีเมธอดเพิ่มเติม เช่น most_common()