简体   繁体   English

使用Python修改collections.Counter的输出

[英]Modifying Output from collections.Counter using Python

I'm using the Python collections library to print out the most common character in a string and how many times it's repeated. 我正在使用Python集合库打印出字符串中最常见的字符以及重复的次数。

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

this is what my result is : 这就是我的结果:

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

which is not what I want. 这不是我想要的。 I want something like 我想要类似的东西

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

does anyone know how to produce the desired result? 有谁知道如何产生预期的结果?

You could try this: 你可以试试这个:

>>> 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')]

I use a list comprehension because list comprehensions are often more efficient than using for clauses and take up far less space. 我使用列表推导,因为列表推导通常比使用for子句更有效for并占用更少的空间。 Per your comment below, though, a for clause would look like what jamylak has suggested: 但是,根据下面的评论, 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')]

Another slightly less readable but still quite pythonic way: 另一个稍微不那么可读但仍然相当pythonic的方式:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM