按两种不同的关键字先后进行排序

在工作或学习中,可能会遇到这样一种排序情况,就是想按照两组数据按先后顺序进行排序。举个简单例子:在python中,一个字典,我想让它先按照键的大小排列,再按照值的大小排列,该怎么做呢?

这里我们举个小例子:
取一段英文“Humans don’t start their thinking from scratch every second. As you read this essay, you understand each word based on your understanding of previous words. You don’t throw everything away and start thinking from scratch again. Your thoughts have persistence.”我们对它进行词频统计,然后再按照词频大小和单词首字母排序。

import collections
text = "Humans don’t start their thinking from scratch every second. As you read this essay, you understand each word based on your understanding of previous words. You don’t throw everything away and start thinking from scratch again. Your thoughts have persistence."
text = text.replace('.', '')
text = text.strip().split()
counter = collections.Counter(text)
# 统计单词的次数
# print(counter)
# print(counter.items())
# (x[1], x[0])表示先按照第二个关键字从小到大排列,再按照第一个关键字的首字母从小到大排列。
counter_new = sorted(counter.items(), key=lambda x: (x[1], x[0]))
print(counter_new)

结果:
[(‘As’, 1), (‘Humans’, 1), (‘You’, 1), (‘Your’, 1), (‘again’, 1), (‘and’, 1), (‘away’, 1), (‘based’, 1), (‘each’, 1), (‘essay,’, 1), (‘every’, 1), (‘everything’, 1), (‘have’, 1), (‘of’, 1), (‘on’, 1), (‘persistence’, 1), (‘previous’, 1), (‘read’, 1), (‘second’, 1), (‘their’, 1), (‘this’, 1), (‘thoughts’, 1), (‘throw’, 1), (‘understand’, 1), (‘understanding’, 1), (‘word’, 1), (‘words’, 1), (‘your’, 1), (‘don’t’, 2), (‘from’, 2), (‘scratch’, 2), (‘start’, 2), (‘thinking’, 2), (‘you’, 2)]
可以,看出它是先将数字进行从小到大排列,在将字母进行从小到大排序。但是,现在问题来了,如果,我想让数字从大到小排列,而字母进行从小到大排列怎么办呢?
其实只需要在x[1]前面加一个负号,改变它的顺序就行。

counter_new = sorted(counter.items(), key=lambda x: (-x[1], x[0]))

结果:
[(‘don’t’, 2), (‘from’, 2), (‘scratch’, 2), (‘start’, 2), (‘thinking’, 2), (‘you’, 2), (‘As’, 1), (‘Humans’, 1), (‘You’, 1), (‘Your’, 1), (‘again’, 1), (‘and’, 1), (‘away’, 1), (‘based’, 1), (‘each’, 1), (‘essay,’, 1), (‘every’, 1), (‘everything’, 1), (‘have’, 1), (‘of’, 1), (‘on’, 1), (‘persistence’, 1), (‘previous’, 1), (‘read’, 1), (‘second’, 1), (‘their’, 1), (‘this’, 1), (‘thoughts’, 1), (‘throw’, 1), (‘understand’, 1), (‘understanding’, 1), (‘word’, 1), (‘words’, 1), (‘your’, 1)]
但是,现在问题又来了,如果我想让数字从小到大排列,而字母进行从大到小排列怎么办呢?是不是在x[0]前面加负号呢,这次就不是了。加了者会报错。
TypeError: bad operand type for unary -: ‘str’
所以,这个问题应该这样来解决:

counter_new = sorted(counter.items(), key=lambda x: (-x[1], x[0]), reverse=True)

结果:
[(‘your’, 1), (‘words’, 1), (‘word’, 1), (‘understanding’, 1), (‘understand’, 1), (‘throw’, 1), (‘thoughts’, 1), (‘this’, 1), (‘their’, 1), (‘second’, 1), (‘read’, 1), (‘previous’, 1), (‘persistence’, 1), (‘on’, 1), (‘of’, 1), (‘have’, 1), (‘everything’, 1), (‘every’, 1), (‘essay,’, 1), (‘each’, 1), (‘based’, 1), (‘away’, 1), (‘and’, 1), (‘again’, 1), (‘Your’, 1), (‘You’, 1), (‘Humans’, 1), (‘As’, 1), (‘you’, 2), (‘thinking’, 2), (‘start’, 2), (‘scratch’, 2), (‘from’, 2), (‘don’t’, 2)]

学习就是不断总结的过程,希望跟小伙伴们一起进步~~

你可能感兴趣的:(Python中常见问题)