鱼C论坛

 找回密码
 立即注册
查看: 3275|回复: 5

一个关于字典的小问题

[复制链接]
发表于 2022-9-16 16:10:48 | 显示全部楼层 |阅读模式
10鱼币
]统计字符串"thebookisborrowedbyjack”中每个字母的出现次数,将结果保存到一个字典对象中,其中key为字母,value为字母出现的次数,对字典中的数据按照字母出现的次数(value值) 进行排序

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2022-9-16 16:45:21 | 显示全部楼层
  1. s="sdluhflqsjidoiqwejfoljsdlkjkaslkdjfjklsdhkweqhfkqwhefksklafglsdfjkashjkldfhklasdhfjksahdfjkhqedhieuwf"
  2. t={}
  3. for x in range(97,123):
  4.     t[chr(x)]=0
  5.   
  6. for x in s:
  7.     t[x]+=1

  8. for x in t:
  9.     if t[x]>0:
  10.         print(x,t[x])
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2022-9-16 16:54:19 | 显示全部楼层
还得按value 排序啊
  1. s="sdluhflqsjidoiqwejfoljsdlkjkaslkdjfjklsdhkweqhfkqwhefksklafglsdfjkashjkldfhklasdhfjksahdfjkhqedhieuwf"
  2. t={}
  3. for x in range(97,123):
  4.     t[chr(x)]=0
  5.   
  6. for x in s:
  7.     t[x]+=1

  8. res=sorted(t.items(),key=lambda kv:kv[1],reverse=True)
  9. for x in res:
  10.     if x[1]>0:
  11.       print(x)
复制代码



('k', 13)
('f', 11)
('d', 10)
('h', 10)
('j', 10)
('l', 10)
('s', 10)
('a', 5)
('e', 5)
('q', 5)
('w', 4)
('i', 3)
('o', 2)
('u', 2)
('g', 1)
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2022-9-16 17:17:54 | 显示全部楼层
希望对你有帮助
  1. #################################方法1用Counter函数
  2. from collections import Counter
  3. str_yuanma='thebookisborrowedbyjack'
  4. count = Counter(str_yuanma)
  5. print(count)
  6. #################################方法2用字符串先转成列表,在用列表统计重复元素放入字典
  7. str_yuanma='thebookisborrowedbyjack'
  8. list=[]
  9. for i in str_yuanma:
  10.     list.append(i)
  11. dict = {}
  12. for key in list:
  13.     dict[key] = dict.get(key, 0) + 1
  14.     # print(list[key])
  15.     # print(dict[key])
  16. print (dict)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2022-9-16 17:47:57 | 显示全部楼层
  1. >>> string = "thebookisborrowedbyjack"
  2. >>> lst = sorted({letter : string.count(letter) for letter in set(string)}.items(), key=lambda x : x[1])
  3. >>> lst
  4. [('d', 1), ('h', 1), ('s', 1), ('c', 1), ('y', 1), ('t', 1), ('i', 1), ('a', 1), ('w', 1), ('j', 1), ('e', 2), ('k', 2), ('r', 2), ('b', 3), ('o', 4)]
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2022-9-16 18:35:56 | 显示全部楼层
  1. s = 'thebookisborrowedbyjack'
  2. res = {}
  3. for i in s:
  4.     res[i] = s.count(i)
  5. res = sorted(res.items(), key=lambda v: v[1])
  6. print(res)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-4-26 22:05

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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