इस लेख में हम देखेंगे कि दी गई सूची में सबसे आम तत्व कैसे ढूंढें। दूसरे शब्दों में, उच्चतम बारंबारता वाला तत्व।
max और count के साथ
हम सूची के अद्वितीय तत्व प्राप्त करने के लिए set फ़ंक्शन लागू करते हैं और फिर सूची में उनमें से प्रत्येक की गिनती रखते हैं। अंत में सबसे अधिक बारंबारता वाला तत्व प्राप्त करने के लिए max फ़ंक्शन लागू करते हैं।
उदाहरण
# दी गई सूची
listA = [45, 20, 11, 50, 17, 45, 50,13, 45]
print("Given List:\n",listA)
res = max(set(listA), key=listA.count)
print("Element with highest frequency:\n",res)
आउटपुट
Given List: [45, 20, 11, 50, 17, 45, 50, 13, 45] Element with highest frequency: 45
Counter के साथ
हम collections से Counter फ़ंक्शन का उपयोग करते हैं। फिर अंतिम परिणाम प्राप्त करने के लिए most_common फ़ंक्शन लागू करते हैं।
उदाहरण
from collections import Counter
# दी गई सूची
listA = [45, 20, 11, 50, 17, 45, 50,13, 45]
print("Given List:\n",listA)
occurrence_count = Counter(listA)
res = occurrence_count.most_common(1)[0][0]
print("Element with highest frequency:\n",res)
आउटपुट
Given List: [45, 20, 11, 50, 17, 45, 50, 13, 45] Element with highest frequency: 45
mode के साथ
यह एक सीधा दृष्टिकोण है जिसमें हम statistics मॉड्यूल से mode फ़ंक्शन का उपयोग करते हैं। यह सीधे हमें परिणाम देता है।
उदाहरण
from statistics import mode
# दी गई सूची
listA = [45, 20, 11, 50, 17, 45, 50,13, 45]
print("Given List:\n",listA)
res = mode(listA)
print("Element with highest frequency:\n",res)
आउटपुट
Given List: [45, 20, 11, 50, 17, 45, 50, 13, 45] Element with highest frequency: 45