1. 程式人生 > >按兩種不同的關鍵字先後進行排序

按兩種不同的關鍵字先後進行排序

在工作或學習中,可能會遇到這樣一種排序情況,就是想按照兩組資料按先後順序進行排序。舉個簡單例子:在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)]

學習就是不斷總結的過程,希望跟小夥伴們一起進步~~