gpt4 book ai didi

python - 如何先根据键对元组元素进行排序,然后根据值对元组元素进行排序

转载 作者:太空宇宙 更新时间:2023-11-03 14:11:29 25 4
gpt4 key购买 nike

<分区>

如何在 python 中对元素元组进行排序,首先根据值,然后根据键。考虑我将用户输入作为字符串的程序。我想找出每个字符的数量并打印字符串中最常见的 3 个字符。

#input string
strr=list(raw_input())
count=dict()

#store the count of each character in dictionary
for i in range(len(strr)):
count[strr[i]]=count.get(strr[i],0)+1

#hence we can't perform sorting on dict so convert it into tuple
temp=list()
t=count.items()

for (k,v) in t:
temp.append((v,k))

temp.sort(reverse=True)

#print 3 most common element
for (v,k) in temp[:3]:
print k,v

关于给予 i/p -aabbbccde

以上代码的输出是:

3 b
2 c
2 a

但我希望输出为:

3 b
2 a
2 c

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com