user1805048
user1805048

Reputation: 63

How to write a function counting number of letter in list?

How to write a function counting number of letter in list? for example:

    letter_list=['a','b','a','c','b','a']


    letter_index={'a':0,'b':1,'c':2}

I want to get a result of:

    ([3,2,1])

Upvotes: 0

Views: 188

Answers (3)

Artsiom Rudzenka
Artsiom Rudzenka

Reputation: 29093

Just one small option:

letter_list=('a','b','a','c','b','a')
def __get_res(lVals):
    unique = set(lVals)
    res = map(lVals.count, unique)
    return (max(unique, key=lVals.count), map(lVals.count, unique))

print __get_res(letter_list)

Upvotes: 0

Aesthete
Aesthete

Reputation: 18848

Try using dict comprehension. Also, letter_list in your example is a tuple, not a list.

>>> letter_list = ['a','b','a','c','b','a']    
>>> {x:letter_list.count(x) for x in letter_list}
{'a': 3, 'c': 1, 'b': 2}

To get the highest occurring item in the list, you could use the Counter module as detailed by @BoppreH, or you could do something like this.

>>> max(set(letter_list), key=letter_list.count)
'b'

Upvotes: 0

BoppreH
BoppreH

Reputation: 10173

To get the most common items in a list, or just count the number of occurrences, use the Counter class.

from collections import Counter
letter_list=('a','b','a','c','b','a')
counter = Counter(letter_list)
print counter.most_common(1)
# Prints 'a' because it's the most common element

And from this you can also get the number of occurrences of each element:

print counter['a'] # Prints 3

print counter.most_common() # Prints [('a', 5), ('r', 2), ('b', 2)]

Upvotes: 1

Related Questions