1

Python コレクション ライブラリを使用して、文字列内で最も一般的な文字と、それが繰り返される回数を出力しています。

import collections
results = collections.Counter("this is fun")
listresults= results.most_common()
print listresults

これが私の結果です:

[(' ', 2), ('i', 2), ('s', 2), ('f', 1), ('h', 1), ('n', 1), ('u', 1), ('t', 1)]

これは私が望むものではありません。私は何かが欲しい

[(2,"i") (2, " "),...]

誰もが望ましい結果を生み出す方法を知っていますか?

4

2 に答える 2

4

これを試すことができます:

>>> from collections import Counter
>>> results = Counter("this is fun")
>>> r = results.most_common()
>>> what_i_want = [(y, x) for x, y in r]
>>> what_i_want
[(2, ' '), (2, 'i'), (2, 's'), (1, 'f'), (1, 'h'), (1, 'n'), (1, 'u'), (1, 't')]

リスト内包表記は多くの場合、句を使用するよりも効率的であり、使用するスペースがはるかに少ないため、リスト内包表記を使用します。forただし、以下のコメントによると、for条項はジャミラークが提案したもののようになります。

>>> what_i_want = []
>>> for x, y in r:
    what_i_want.append((y, x))
>>> what_i_want
[(2, ' '), (2, 'i'), (2, 's'), (1, 'f'), (1, 'h'), (1, 'n'), (1, 'u'), (1, 't')]
于 2013-04-27T01:44:19.753 に答える
0

少し読みにくいが、まだ非常にpythonicな方法:

import collections
results = collections.Counter("this is fun")
listresults= results.most_common()
print listresults
print zip(*reversed(zip(*listresults)))
于 2013-04-27T15:32:12.567 に答える