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

Python - นับจำนวนค่าที่ไม่ซ้ำกัน (Unique Values Count) ของลิสต์


ตัวอย่าง

โค้ดด้านล่างนับจำนวนค่าที่ไม่ซ้ำกันในลิสต์โดยใช้ลิสต์ช่วยเก็บค่าที่เจอแล้ว

my_list = [12, 33, 33, 54, 84, 16, 16, 16, 58]
print("The list is :")
print(my_list)
filtered_list = []
elem_count = 0
for item in my_list:
    if item not in filtered_list:
        elem_count += 1
        filtered_list.append(item)
print("The result is :")
print(elem_count)

ผลลัพธ์

The list is : [12, 33, 33, 54, 84, 16, 16, 16, 58]
The result is : 6

คำอธิบาย

  • กำหนดลิสต์และแสดงผล

  • สร้างลิสต์ว่าง filtered_list และตัวนับ elem_count = 0

  • วนลูปแต่ละ item ถ้ายังไม่มีใน filtered_list ให้เพิ่มตัวนับและ append เข้า filtered_list

  • แสดงจำนวนค่าที่ไม่ซ้ำกัน