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

องค์ประกอบที่มีความถี่มากที่สุดในลิสต์ใน Python

การวิเคราะห์ข้อมูลทางสถิติหลายอย่างพยายามหาค่าที่มีความถี่สูงสุดในลิสต์ค่าที่กำหนด Python มีหลายวิธีที่เราสามารถหาค่าดังกล่าวจากลิสต์ที่กำหนด ด้านล่างคือวิธีการต่างๆ

ใช้ Counter

ฟังก์ชัน Counter จากโมดูล collections มีตัวเลือกที่สามารถหาองค์ประกอบที่พบบ่อยที่สุดในลิสต์ที่กำหนดได้โดยตรง เรามีฟังก์ชัน most_common ที่เราส่งพารามิเตอร์ 1 สำหรับองค์ประกอบเดียวที่มีความถี่สูงสุด และส่ง 2 หากต้องการสององค์ประกอบที่มีความถี่สูงสุด

ตัวอย่าง

from collections import Counter
# Given list
listA = ['Mon', 'Tue','Mon', 9, 3, 3]
print("Given list : ", listA)
# Adding another element for each element
Newlist1 = Counter(listA).most_common(1)
Newlist2 = Counter(listA).most_common(2)
# Results
print("New list after duplication: ", Newlist1)
print("New list after duplication: ", Newlist2)

Output

การรันโค้ดข้างต้นให้ผลลัพธ์ดังนี้ -

Given list : ['Mon', 'Tue', 'Mon', 9, 3, 3]
New list after duplication: [('Mon', 2)]
New list after duplication: [('Mon', 2), (3, 2)]

ใช้ mode

Mode เป็นฟังก์ชันทางสถิติที่มีในโมดูล statistics ของ Python มันจะให้ผลลัพธ์เป็นองค์ประกอบที่มีความถี่สูงสุด หากมีหลายองค์ประกอบเช่นนั้น องค์ประกอบที่พบก่อนที่มีความถี่สูงสุดจะเป็นผลลัพธ์

ตัวอย่าง

from statistics import mode
# Given list
listA = ['Mon', 'Tue','Mon', 9, 3, 3]
listB = [3, 3, 'Mon', 'Tue','Mon', 9]
print("Given listA : ", listA)
print("Given listB : ", listB)
# Adding another element for each element
Newlist1 = mode(listA)
Newlist2 = mode(listB)
# Results
print("New listA after duplication: ", Newlist1)
print("New listB after duplication: ", Newlist2)

Output

การรันโค้ดข้างต้นให้ผลลัพธ์ดังนี้ -

Given listA : ['Mon', 'Tue', 'Mon', 9, 3, 3]
Given listB : [3, 3, 'Mon', 'Tue', 'Mon', 9]
New listA after duplication: Mon
New listB after duplication: 3