Python:如何计算字符串列表?

时间:2017-09-03 03:35:42

标签: python

我试图编写一个小程序来计算字符串列表,并按字母顺序打印所述字符串并显示出现次数。

这是我到目前为止所做的:

from collections import Counter
def funct(list):
  count = Counter(list)
  print(count)

funct(['a','c','a','a','c','b'])

当前输出为:

计数器({' a':3,' c':2,' b':1})

如何重新格式化输出,包括对字符串进行排序?

所需的输出是:

a 3

b 1

c 2

2 个答案:

答案 0 :(得分:3)

from collections import Counter
def funct(list):
  count = Counter(list)
  for item in sorted(count.items()):
      print(item[0], item[1])

funct(['a','c','a','a','c','b'])

<强>输出:

a 3
b 1
c 2

答案 1 :(得分:0)

您可以在打印前使用已排序的功能:

for keys,values in sorted(count.items()):