## やりたいこと
2重リスト内から、最も頻繁に出るリストを求めたいと思っています。
仮にlist = [["a","b","a"],["a","b","a"],["b","b","b"]]
というリストがある場合に、最頻値として["a","b","a"]というリストを取得したいです。
※要素"b"を取得したいわけではありません。
## 試したこととエラー内容
その1
import collections import itertools l = [["a","b","a"],["a","b","a"],["b","b","b"]] counter = collections.Counter(l) mode_v = counter.most_common()[0][-1] it = itertools.takewhile( lambda kv: kv[-1] == mode_v, counter.most_common() ) print(*(k for k, v in it)) ↓↓↓ --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-43-7a37c6dcd6b5> in <module>() 3 4 l = [["a","b","a"],["a","b","a"],["b","b","b"]] ----> 5 counter = collections.Counter(l) 6 7 mode_v = counter.most_common()[0][-1] 1 frames /usr/lib/python3.6/collections/__init__.py in update(*args, **kwds) 620 super(Counter, self).update(iterable) # fast path when counter is empty 621 else: --> 622 _count_elements(self, iterable) 623 if kwds: 624 self.update(kwds) TypeError: unhashable type: 'list'
その2
import collections l = [["a","b","a"],["a","b","a"],["b","b","b"]] counted = collections.Counter(l) ret = [letter for letter,count in counted.most_common() if count == counted.most_common()[0][1]] print(ret) ↓↓↓ --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-41-1aaaf953c9ea> in <module>() 1 import collections 2 l = [["a","b","a"],["a","b","a"],["b","b","b"]] ----> 3 counted = collections.Counter(l) 4 ret = [letter for letter,count in counted.most_common() if count == counted.most_common()[0][1]] 5 print(ret) # ['a', 'c'] 1 frames /usr/lib/python3.6/collections/__init__.py in update(*args, **kwds) 620 super(Counter, self).update(iterable) # fast path when counter is empty 621 else: --> 622 _count_elements(self, iterable) 623 if kwds: 624 self.update(kwds) TypeError: unhashable type: 'list'
どちらも同じようなエラーになっているようです。エラーを直す形でも新たコードを書いてくださる形でも結構ですので、回答よろしくお願いします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/06/07 05:02
2019/06/07 05:26
2019/06/07 05:56