Python 格式化 count() 方法

Python format count() method

我创建了一个应用程序,可以帮助破解学校作业的密码。我必须使用 .count() 方法来计算一个字母在单词列表中出现的次数。这是输出:

Counter({'\n': 9, '#': 8, '&': 7, '3': 6, '*': 4, '%': 4, '1': 3, '8': 3, '0': 3, ')': 2, '+': 2, '4': 2, '7': 2, '2': 2, '-': 2, '/': 1, ',': 1, '$': 1, '6': 1, '5': 1, '!': 1, '.': 1, ':': 1, '"': 1, "'": 1, '9': 1})

有什么方法可以将其格式化以使其看起来更好并且更易于理解吗?

for keys, values in YourDictionaryHere.items():
    print keys, values

这是你想要的吗?

from collections import Counter

stuff = Counter({'\n': 9, '#': 8, '&': 7, '3': 6, '*': 4, '%': 4, '1': 3, '8': 3, '0': 3, ')': 2, '+': 2, '4': 2, '7': 2, '2': 2, '-': 2, '/': 1, ',': 1, '$': 1, '6': 1, '5': 1, '!': 1, '.': 1, ':': 1, '"': 1, "'": 1, '9': 1})

stuff = dict(stuff)
line = []
for i,kv in enumerate(stuff.iteritems(), start=1):
    line.append("%s : %d" % kv)
    if i % 4 == 0:
        print line
        line = []

if line: print line

生产:

['\n : 9', '! : 1', '# : 8', '" : 1']
['% : 4', '$ : 1', "' : 1", '& : 7']
[') : 2', '+ : 2', '* : 4', '- : 2']
[', : 1', '/ : 1', '. : 1', '1 : 3']
['0 : 3', '3 : 6', '2 : 2', '5 : 1']
['4 : 2', '7 : 2', '6 : 1', '9 : 1']
['8 : 3', ': : 1']

要在每行中获取更多条目,请更改 i % 4 行。