鱼C论坛

 找回密码
 立即注册
查看: 1003|回复: 2

[已解决]python关于字符数统计问题

[复制链接]
发表于 2019-10-16 21:08:02 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
从键盘输入一串字符,统计输出出现次数最多的前3个字符及次数,并输出总共出现了多少种字符
str=input()
space=0
number=0
zimu=0
other=0
m=0
for i in str:
    if i.isspace():
        space=space+1
    elif i.isalpha():
        zimu=zimu+1
    elif i.isnumeric():
        number=number+1
    else:
        other=other+1
if space>0:
    m=m+1
if zimu>0:
    m=m+1
if number>0:
    m=m+1
if other>0:
    m=m+1
print("字母有{}空格有{}其他有{}数字有{}总共出现了{}种字符".format(zimu,space,other,number,m))

感觉做得不对  跟题目不对应  字符数应该不应该像我这样分类吧 另外不知道怎么统计前三的字符
最佳答案
2019-10-17 20:12:25
  1. # -*- coding: utf-8 -*-
  2. def statistics(string):
  3.     appear_dict = {}
  4.     for i in string:
  5.         if i not in appear_dict:
  6.             appear_dict[i] = 1
  7.         else:
  8.             appear_dict[i] += 1
  9.     return appear_dict.items()


  10. str1 = input("请输入字符:")
  11. appear = statistics(str1)
  12. appear = list(sorted(appear, key=lambda x: x[1], reverse=True))
  13. print("出现最多的 3 种字符分别是:")
  14. for i in range(3):
  15.     try:
  16.         print(f"{appear[i][0]} : {appear[i][1]}")
  17.     except IndexError:
  18.         break

  19. print(f"一共出现了 {len(appear)} 种字符")
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2019-10-16 23:45:31 | 显示全部楼层
可以这样
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-10-17 20:12:25 | 显示全部楼层    本楼为最佳答案   
  1. # -*- coding: utf-8 -*-
  2. def statistics(string):
  3.     appear_dict = {}
  4.     for i in string:
  5.         if i not in appear_dict:
  6.             appear_dict[i] = 1
  7.         else:
  8.             appear_dict[i] += 1
  9.     return appear_dict.items()


  10. str1 = input("请输入字符:")
  11. appear = statistics(str1)
  12. appear = list(sorted(appear, key=lambda x: x[1], reverse=True))
  13. print("出现最多的 3 种字符分别是:")
  14. for i in range(3):
  15.     try:
  16.         print(f"{appear[i][0]} : {appear[i][1]}")
  17.     except IndexError:
  18.         break

  19. print(f"一共出现了 {len(appear)} 种字符")
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-16 02:34

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表