เรามีรายการที่มีองค์ประกอบเป็นตัวเลข องค์ประกอบหลายอย่างมีอยู่หลายครั้ง เราต้องการสร้างรายการย่อยเพื่อให้ความถี่ของแต่ละองค์ประกอบพร้อมกับองค์ประกอบเอง
มี for และต่อท้าย
ในแนวทางนี้ เราจะเปรียบเทียบแต่ละองค์ประกอบในรายการกับองค์ประกอบอื่นๆ ทั้งหมดหลังจากนั้น หากมีการจับคู่ การนับจะเพิ่มขึ้น และทั้งองค์ประกอบและการนับจะถูกทำให้เป็นส่วนย่อย รายการจะถูกจัดทำขึ้นซึ่งควรมีองค์ประกอบที่แสดงทุกองค์ประกอบและความถี่
ตัวอย่าง
def occurrences(list_in):
for i in range(0, len(listA)):
a = 0
row = []
if i not in listB:
for j in range(0, len(listA)):
# matching items from both positions
if listA[i] == listA[j]:
a = a + 1
row.append(listA[i])
row.append(a)
listB.append(row)
# Eliminate repetitive list items
for j in listB:
if j not in list_uniq:
list_uniq.append(j)
return list_uniq
# Caller code
listA = [13,65,78,13,12,13,65]
listB = []
list_uniq = []
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]]
มีเคาน์เตอร์
เราใช้วิธีการนับจากโมดูลการรวบรวม มันจะให้การนับของทุกองค์ประกอบในรายการ จากนั้นเราจะประกาศรายการว่างใหม่และเพิ่มคู่ค่าคีย์สำหรับแต่ละรายการในรูปแบบขององค์ประกอบและนับเป็นรายการใหม่
ตัวอย่าง
from collections import Counter
def occurrences(list_in):
c = Counter(listA)
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]]