我正在使用 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, " "),...]
有谁知道如何产生预期的结果?
最佳答案
你可以试试这个:
>>> 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')]
我使用 list comprehension因为列表推导通常比使用 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')]
关于python - 使用 Python 修改 collections.Counter 的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16247447/