Help us understand the problem. What is going on with this article?

# リストの最頻値を求めたいがstatistics.mode()が例外を返してくる

More than 1 year has passed since last update.

### statistics.mode()メソッドはリストの最頻値を返してくれます

```>>> import statistics
>>> l = [1,1,2,3] #最頻値は1
>>> statistics.mode(l)
1
```

OKですね
ところがリスト内に最頻値が複数存在すると，例外を返す仕様となっています

```>>> l = [1,1,2,2,3] #最頻値は1と2
>>> statistics.mode(l)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/anaconda3/lib/python3.6/statistics.py", line 507, in mode
'no unique mode; found %d equally common values' % len(table)
statistics.StatisticsError: no unique mode; found 2 equally common values
>>>
```

### どうしよう

collections.Counter()メソッドが使えそうです

```>>> l
[1, 1, 2, 2, 3]
>>> import collections
>>> collections.Counter(l).most_common() #(要素，出現回数)を出現回数順に並び替えたタプルを返す
[(1, 2), (2, 2), (3, 1)]
```

とりあえず何か一つ最頻値が欲しい場合は，

```>>> collections.Counter(l).most_common()[0][0]
1
```

で良さそうです

Why not register and get more from Qiita?
1. We will deliver articles that match you
By following users and tags, you can catch up information on technical fields that you are interested in as a whole
2. you can read useful information later efficiently
By "stocking" the articles you like, you can search right away