jxba
# 计算出以下字符串,每个字符出现的次数
a = "hello,world!"
print(\'a=\',a)

#办法1
print ("统计a中各项的个数,办法1(字典):")
dicta = {}
for i in a:
    dicta[i] = a.count(i)
print (dicta)


# 办法2
print ("统计a中各项的个数,办法2(collections的counter):")
from collections import Counter
print(Counter(a))


# 办法3
print ("统计a中各项的个数,办法3(count方法):")
for i in a:
    print("%s:%d" %(i,a.count(i)))    #用count方法计算各项数量,简单打印出来而已

# 办法4(结果同3)
print ("统计a中各项的个数,办法4(列表count方法):")
lista = list(a)                           #字符串转为列表
print (\'lista:\',lista)
for i in lista:
    print("%s:%d" %(i,lista.count(i)))    #用列表的count方法计算各项数量

打印结果:

a= hello,world!
统计a中各项的个数,办法1(字典):
{\'h\': 1, \'e\': 1, \'l\': 3, \'o\': 2, \',\': 1, \'w\': 1, \'r\': 1, \'d\': 1, \'!\': 1}
统计a中各项的个数,办法2(collections的counter):
Counter({\'l\': 3, \'o\': 2, \'h\': 1, \'e\': 1, \',\': 1, \'w\': 1, \'r\': 1, \'d\': 1, \'!\': 1})
统计a中各项的个数,办法3(count方法):
h:1
e:1
l:3
l:3
o:2
,:1
w:1
o:2
r:1
l:3
d:1
!:1
统计a中各项的个数,办法4(列表count方法):
lista: [\'h\', \'e\', \'l\', \'l\', \'o\', \',\', \'w\', \'o\', \'r\', \'l\', \'d\', \'!\']
h:1
e:1
l:3
l:3
o:2
,:1
w:1
o:2
r:1
l:3
d:1
!:1

Process finished with exit code 0

 

分类:

技术点:

相关文章:

  • 2021-04-09
  • 2018-03-07
  • 2021-11-29
  • 2021-11-29
  • 2020-04-30
  • 2021-07-16
  • 2021-07-03
  • 2022-01-02
猜你喜欢
  • 2021-07-28
  • 2021-12-28
  • 2021-08-12
  • 2020-01-16
  • 2018-07-03
  • 2021-12-05
  • 2021-09-10
相关资源
相似解决方案