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

2024-04-18 23:23:26 发布

您现在位置: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

Tags: 字符串from程序列表顺序count字母counter
2条回答

打印前可以使用排序函数:

for keys,values in sorted(count.items()):
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

相关问题 更多 >