wy521@ 发表于 2022-9-16 16:10:48

一个关于字典的小问题

]统计字符串"thebookisborrowedbyjack”中每个字母的出现次数,将结果保存到一个字典对象中,其中key为字母,value为字母出现的次数,对字典中的数据按照字母出现的次数(value值) 进行排序

wp231957 发表于 2022-9-16 16:45:21

s="sdluhflqsjidoiqwejfoljsdlkjkaslkdjfjklsdhkweqhfkqwhefksklafglsdfjkashjkldfhklasdhfjksahdfjkhqedhieuwf"
t={}
for x in range(97,123):
    t=0

for x in s:
    t+=1

for x in t:
    if t>0:
      print(x,t)

wp231957 发表于 2022-9-16 16:54:19

还得按value 排序啊
s="sdluhflqsjidoiqwejfoljsdlkjkaslkdjfjklsdhkweqhfkqwhefksklafglsdfjkashjkldfhklasdhfjksahdfjkhqedhieuwf"
t={}
for x in range(97,123):
    t=0

for x in s:
    t+=1

res=sorted(t.items(),key=lambda kv:kv,reverse=True)
for x in res:
    if x>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)

wyh551202 发表于 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 = dict.get(key, 0) + 1
    # print(list)
    # print(dict)
print (dict)

ZhKQYu 发表于 2022-9-16 17:47:57

>>> string = "thebookisborrowedbyjack"
>>> lst = sorted({letter : string.count(letter) for letter in set(string)}.items(), key=lambda x : x)
>>> 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)]

临时号 发表于 2022-9-16 18:35:56

s = 'thebookisborrowedbyjack'
res = {}
for i in s:
    res = s.count(i)
res = sorted(res.items(), key=lambda v: v)
print(res)
页: [1]
查看完整版本: 一个关于字典的小问题