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条款看起来像 jamylak 所建议的:

>>> 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 回答