हमारे पास एक सूची है जिसके तत्व संख्यात्मक हैं। कई तत्व कई बार मौजूद होते हैं। हम उप सूची बनाना चाहते हैं ताकि तत्वों के साथ-साथ प्रत्येक तत्व की आवृत्ति भी हो।
के लिए और संलग्न करें
इस दृष्टिकोण में हम सूची में प्रत्येक तत्व की तुलना उसके बाद के अन्य तत्वों से करेंगे। यदि कोई मेल है तो गिनती बढ़ा दी जाएगी और तत्व और गिनती दोनों को निर्वाह बना दिया जाएगा। सूची बनाई जाएगी जिसमें हर तत्व और उसकी आवृत्ति दिखाते हुए निर्वाह होना चाहिए।
उदाहरण
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]]