python - 使用 Python 修改 collections.Counter 的输出

标签 python collections

我正在使用 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/

相关文章:

python - 我怎样才能解决下面的这些错误?

python - python 如何知道何时返回生成器?

python - 如果Python中存在分隔符,如何提取字符串

安装了Python3.5但pip3指向python3.6

collections - 为什么不能收集一定范围的字符?

.NET集合和大对象堆(LOH)

Java - 什么可以替代 Google Guava Ranges?

java - Collections.sort 不起作用

java - 如何将数字从最小到最大排序 - Java?

Python heapq heappush 多元素数组真值不明确使用 a.any() 或 a.all()