鱼C论坛

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

一个关于字典的小问题

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

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

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

for x in t:
    if t[x]>0:
        print(x,t[x])
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

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

res=sorted(t.items(),key=lambda kv:kv[1],reverse=True)
for x in res:
    if x[1]>0:
      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)
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2022-9-16 17:17:54 | 显示全部楼层
希望对你有帮助
#################################方法1用Counter函数
from collections import Counter
str_yuanma='thebookisborrowedbyjack'
count = Counter(str_yuanma)
print(count)
#################################方法2用字符串先转成列表,在用列表统计重复元素放入字典
str_yuanma='thebookisborrowedbyjack'
list=[]
for i in str_yuanma:
    list.append(i)
dict = {}
for key in list:
    dict[key] = dict.get(key, 0) + 1
    # print(list[key])
    # print(dict[key])
print (dict)
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2022-9-16 17:47:57 | 显示全部楼层
>>> string = "thebookisborrowedbyjack"
>>> lst = sorted({letter : string.count(letter) for letter in set(string)}.items(), key=lambda x : x[1])
>>> lst
[('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)]
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2022-9-16 18:35:56 | 显示全部楼层
s = 'thebookisborrowedbyjack'
res = {}
for i in s:
    res[i] = s.count(i)
res = sorted(res.items(), key=lambda v: v[1])
print(res)
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-9-28 18:20

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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