Reputation: 167
I am trying to count the frequency of the elements in the list. The below code is from a Data Science book, i am not able to understand the meaning of (0)[1] Please someone explain me.
from collections import Counter
def raw_majority_vote(labels):
votes=Counter(labels)
winner,x=votes.most_common(1)[0]
return winner,x
l=[12,9,3,4,19,11,12,16,19,19,12,12,12,87,12,54,12]
raw_majority_vote(l)
Upvotes: 0
Views: 229
Reputation: 1061
just to consolidate what's already mentioned in the comments.
most_common(n)
returns a list of tuples in sorted order with the parameter n
specifying how many of the most common objects are returned.
for example
most_common(2)
will return the top 2 most common objects, as a tuple with the first element of the tuple being the object name and the second element of the tuple being the count of them.
Now you know that result = most_common(2)
returns a list of length 2, with tuples of the object and the count.
You can index into that list with []
and subsequently into the tuple with another set of []
. most_common(2)[1]
gets you the second most common element in the list and it's count.
In your example most_common(1)
returns a list of length 1. List indexes start at 0
, so to get the first tuple you use most_common(1)[0]
most_common(1)[0][0]
.most_common(1)[0][1]
Upvotes: 1
Reputation: 31
from collections import Counter
def raw_majority_vote(labels):
votes=Counter(labels)
winner,x=votes.most_common(1)[0]
print(type(votes.most_common()))
print(votes.most_common())
print(type(votes.most_common(1)[0]))
print(votes.most_common(1)[0])
print(type(votes.most_common(1)[0][0]))
print(votes.most_common(1)[0][0])
return winner,x
l=[12,9,3,4,19,11,12,16,19,19,12,12,12,87,12,54,12]
raw_majority_vote(l)
it will easier to understand as above showed
Upvotes: 2