ในบทช่วยสอนนี้ เราจะเขียนโปรแกรมที่ค้นหาความถี่ขององค์ประกอบทั้งหมดในอาร์เรย์ เราสามารถค้นหามันได้หลากหลายวิธี เรามาสำรวจกันทั้งสองแบบกันเลย
การใช้ dict
-
เริ่มต้นอาร์เรย์
-
เริ่มต้น dict . ที่ว่างเปล่า .
-
ทำซ้ำในรายการ
-
หากองค์ประกอบไม่อยู่ใน dict ให้ตั้งค่าเป็น 1 .
-
อย่างอื่นเพิ่มค่าโดย 1 .
-
-
พิมพ์องค์ประกอบและความถี่โดยวนซ้ำบน dict
ตัวอย่าง
มาดูโค้ดกันเลย
# intializing the list
arr = [1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3]
# initializing dict to store frequency of each element
elements_count = {}
# iterating over the elements for frequency
for element in arr:
# checking whether it is in the dict or not
if element in elements_count:
# incerementing the count by 1
elements_count[element] += 1
else:
# setting the count to 1
elements_count[element] = 1
# printing the elements frequencies
for key, value in elements_count.items():
print(f"{key}: {value}") ผลลัพธ์
หากคุณเรียกใช้โปรแกรมข้างต้น คุณจะได้ผลลัพธ์ดังต่อไปนี้
1: 3 2: 4 3: 5
มาดูแนวทางที่สองโดยใช้คลาส Counter ของโมดูล Collection
การใช้คลาสเคาน์เตอร์
-
นำเข้า คอลเลกชัน โมดูล
-
เริ่มต้นอาร์เรย์
-
ส่งรายการไปที่ เคาน์เตอร์ ระดับ. และเก็บผลลัพธ์ไว้ในตัวแปร
-
พิมพ์องค์ประกอบและความถี่โดยวนซ้ำผลลัพธ์
ตัวอย่าง
ดูโค้ดด้านล่าง
# importing the collections module
import collections
# intializing the arr
arr = [1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3]
# getting the elements frequencies using Counter class
elements_count = collections.Counter(arr)
# printing the element and the frequency
for key, value in elements_count.items():
print(f"{key}: {value}") ผลลัพธ์
หากคุณเรียกใช้โค้ดด้านบน คุณจะได้ผลลัพธ์เหมือนกับโค้ดก่อนหน้า
1: 3 2: 4 3: 5
บทสรุป
หากคุณมีข้อสงสัยใดๆ ในบทแนะนำ โปรดระบุในส่วนความคิดเห็น