[英]Modifying Output from collections.Counter using Python
我正在使用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')]
我使用列表推导,因为列表推导通常比使用for
子句更有效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')]
另一个稍微不那么可读但仍然相当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.