キーでpythonでカウンタを並べ替え:私はこのようなビットに見えるカウンター持っ
Counter: {('A': 10), ('C':5), ('H':4)}
私は特にアルファベット順でキーにソートしたい、NOT counter.most_common()
ことではあるが任意のこれを達成する方法?
キーでpythonでカウンタを並べ替え:私はこのようなビットに見えるカウンター持っ
Counter: {('A': 10), ('C':5), ('H':4)}
私は特にアルファベット順でキーにソートしたい、NOT counter.most_common()
ことではあるが任意のこれを達成する方法?
ちょうどsorted使用:
x = ['a', 'b', 'c', 'c', 'c', 'd', 'd']
counts = collections.Counter(x)
counts.most_common(len(counts))
これはcollections.Counterで利用可能なmost_common機能を使用しています。
>>> from collections import Counter
>>> counter = Counter({'A': 10, 'C': 5, 'H': 7})
>>> counter.most_common()
[('A', 10), ('H', 7), ('C', 5)]
>>> sorted(counter.items())
[('A', 10), ('C', 5), ('H', 7)]
私は、dictのイテレータが値ではなくキーを生成することを知っているので、キーはソートされます。 –
>>> from operator import itemgetter
>>> from collections import Counter
>>> c = Counter({'A': 10, 'C':5, 'H':4})
>>> sorted(c.items(), key=itemgetter(0))
[('A', 10), ('C', 5), ('H', 4)]
これはうまくいきますが、itemgetterはタプルリストやリストリストをソートするのに便利ですが、dictでは無意味です。sorted(c)はsorted(c.keys())と等価です。 –
は、Python 3では、あなたがcollections.Counterのmost_common機能を使用することができますn
の最も一般的なキーのキーとカウントを見つけることができます。
カウンタは基本的に単なる辞書なので、これは実際にはこれと重複しているはずです:http://stackoverflow.com/questions/9001509/python-dictionary-sort-by-key –
印刷しますか?ソートされた順序で? –