Modal value of an array

Paddy paddy3118 at googlemail.com
Thu Mar 29 01:06:31 EDT 2007


On Mar 29, 4:40 am, "datta.abhi... at gmail.com"
<datta.abhi... at gmail.com> wrote:
> Hi
>
>  How can I find out the modal value in an array. That is the value
> which occurs maximum time in the sequence ..
>
> e.g. if my array has values like [2,3,2,2,2,4,2,2]  definitely the
> maximum time 2 occurs in the array. so this function should be able to
> return 2 as a result ..
>
> So is there any function in built in python which can do that ?
>
> Thanks
>
> Abhirup

With the same assumptions as Ben Finney, I came up with this:

>>> import operator
>>> foo = ["spam", "eggs", "spam", "spam", "spam", "beans", "eggs"]
>>> count = {}
>>> for item in foo: count[item] = count.get(item, 0) +1
...
>>> maxitem = max(count.items(), key= operator.itemgetter(1))
>>> maxitem
('spam', 4)
>>>

I was trying to minimise the iterations through the list.

- Paddy.




More information about the Python-list mailing list