如何在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
Run Code Online (Sandbox Code Playgroud)
给予i/p -aabbbccde
上述代码的输出是:
3 b
2 c
2 a
Run Code Online (Sandbox Code Playgroud)
但我希望输出为:
3 b
2 a
2 c
Run Code Online (Sandbox Code Playgroud)