2016-08-30 17 views
-1

私は単語を含むリストを持っています。私は私のリストの中で最も頻繁に言葉を知りたい。コレクションパッケージから 'counter'を使ってみました。リスト内で最も頻繁に出現する単語を検索します(頻度なし)

result = Counter(z).most_common(5) 

この結果が得られました。

result 
>>[('abc', 893), ('op', 198), ('bff', 172), ('ppf', 140), ('request', 119)] 

しかし、私は言葉が欲しいだけで、頻度はありません。それに付いている。 resultからそれらを抽出するために理解

['abc','op','bff','ppf','request'] 

答えて

0

使用リストのように:

print([res[0] for res in result]) 
0

あなたは、インデックスとリスト内包表記を使用することができます。

result = Counter(z).most_common(5) 
result = [i[0] for i in result] 

または1行で:

result = [i[0] for i in Counter(z).most_common(5)] 
0

からHEREカウンタがdefaultdictより遅い。パフォーマンスが重要である場合は、これを試してみてください。

import operator 
from collections import defaultdict 

counter = defaultdict(int) 
foods = ['soy', 'dairy', 'gluten', 'soy'] 
for k in foods: 
    counter[k] += 1 
most_common = 5 
# counter includes a dictionary(without order) 
# here we sort dictionary(this may needs more time than above link shows): 
result = list(zip(*sorted(counter.items(), key=operator.itemgetter(1), reverse=True)[:most_common]))[0] 
+0

それは私のように出力を得た。..出力順序はランダムですです: '[「グルテン」、「酪農」]'しかし、それは '[「大豆」、「酪農」]でなければなりません'' soy ''、 '' soy ':2、 '' soy' '、 '' gluten' ''、 '' soy ''、 '' gluten '''と表示されます。 '乳製品':1}) ' –

+0

@KalpeshDusane申し訳ありません。コードが更新されました: –

+0

defaultdictの代わりに通常の辞書を使用できますか?私が試み、それが動作します: 'カウンタ= {} 食品= [ '大豆'、 '乳製品'、 'グルテン'、 '大豆'] kについて食品中: \t K場合カウンターで: \t \tカウンタ[K ] + = 1 \t else: \t \t counter [k] = 1'性能に違いはありますか? –

関連する問題