如何首先根据键然后根据值对元组元素进行排序 [英] how to sort tuple element first on the basis of key and then on the basis of value

查看:43
本文介绍了如何首先根据键然后根据值对元组元素进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to sort a tuple of elements in python, first on the basis of value and then on the basis of key. Consider the program in which I am taking input from the user as a string. I want to find out the count of each character and print the 3 most common characters in a string.

#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

on giving the i/p -aabbbccde

以上代码的输出为:

3 b
2 c
2 a

但我希望输出为:

3 b
2 a
2 c

推荐答案

对元组列表进行排序,第一个值按降序排列 (reverse=True),第二个值按升序排列 (reverse=False,默认情况下).这是一个 MWE.

Sort a list of tuples, the first value in descending order (reverse=True) and the second value in ascending order (reverse=False, by default). Here is a MWE.

lists = [(2, 'c'), (2, 'a'), (3, 'b')]

result = sorted(lists, key=lambda x: (-x[0], x[1])) # -x[0] represents descending order

print(result)
# Output
[(3, 'b'), (2, 'a'), (2, 'c')]

<小时>

使用collections.Counter计算字符串中每个字母的频率.


It is straightforward to use collections.Counter to count each letter's frequency in a string.

import collections

s = 'bcabcab'

# If you don't care the order, just use `most_common`
#most_common = collections.Counter(s).most_common(3)

char_and_frequency = collections.Counter(s)
result = sorted(char_and_frequency.items(), key=lambda x:(-x[1], x[0]))[:3]    # sorted by x[1] in descending order, x[0] in ascending order

print(result)
# Output
[('b', 3), ('a', 2), ('c', 2)]

这篇关于如何首先根据键然后根据值对元组元素进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆