[Tutor] get the mode of a list
Terry Carroll
carroll at tjc.com
Fri Oct 22 02:46:14 CEST 2004
On Thu, 21 Oct 2004, Nick Lunt wrote:
> I want to return the mode of a list, just to clarify the mode is the most
> frequently occurring member of a list in my case.
Here's my take. I'll bet it has some limitations I'm not aware of. It
returns a list with two elements. The first is the number of times the
mode value occurs, and the second is a list of modes.
For the example below, mode([1, 2, 4, 2, 4, 5, 2, 4, 100]), where 2 and 3
are the modes, each occuring 3 times, it returns [3, [2, 4]]
def mode(mylist):
_hist_dict={}
for item in mylist:
_hist_dict[item]=_hist_dict.get(item,0)+1
_modevalue=max(_hist_dict.values())
_returned_list=[]
for key in _hist_dict.keys():
if _hist_dict[key] == _modevalue:
_returned_list.append(key)
return [_modevalue, _returned_list]
if __name__ == "__main__":
testlist = [1, 2, 4, 2, 4, 5, 2, 4, 100]
modelist = mode(testlist)
print modelist
More information about the Tutor
mailing list