我正在使用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, " "),...]
有谁知道如何产生预期的结果?
答案 0 :(得分: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')]
我使用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')]
答案 1 :(得分:0)
另一种稍微不那么可读但仍然相当pythonic的方式:
import collections
results = collections.Counter("this is fun")
listresults= results.most_common()
print listresults
print zip(*reversed(zip(*listresults)))