# 需要排序的內容,要求按照數值由低到高進行排序
att_value = [{'萬科': '0.7318349007046632'}, {'影視': '0.5518031664124353'}, {'湖南衛視': '0.5666107580617218'}, {'竇驍': '0.7329163786180936'}, {'鬱亮': '0.7237278818910436'}]
# 方法:先將dict_vaules強轉爲str變成"dict_values(['0.7318349007046632'])"這種,再截取字符串[14:-3]然後強轉爲float值排序
sorted(att_value, key=lambda item:float(str(item.values())[14:-3]), reverse=True)
結果:
<class 'list'>: [
{'竇驍': '0.7329163786180936'},
{'萬科': '0.7318349007046632'},
{'鬱亮': '0.7237278818910436'},
{'湖南衛視': '0.5666107580617218'},
{'影視': '0.5518031664124353'}]
原理:
Python3自定義key函數排序 以下文章引用自這裏
sorted(iterable, key=None, reverse=False)
- reverse是一個布爾值。如果設置爲True,列表元素將被倒序排列,默認爲False
- key接受一個函數,這個函數只接受一個元素,默認爲None
Key的作用原理
- 在python3中,待比較元素x通過custom_key函數轉化爲Python能比較的值custom_key(x),進而再基於返回值進行排序。
例子1:
my_alphabet = ['a', 'b', 'c']
def custom_key(word):
numbers = []
for letter in word:
numbers.append(my_alphabet.index(letter))
return numbers
python中的整數列表能夠比較大小
custom_key('cbaba')==[2, 1, 0, 1, 0]
x=['cbaba', 'ababa', 'bbaa']
x.sort(key=custom_key)
例子2
students = [('john', 'A', 15), ('jane', 'B', 12), ('dave','B', 10)]
sorted(students,key=lambda x: x[2]) #按照年齡來排序
關於lambda表達式
例子3
默認sorted([True, False])==[False, True] (False=0 < True=1)
一個字符串排序,排序規則:小寫<大寫<奇數<偶數
# 元組內(e1, e2, e3)的優先級排列爲: e1 > e2 > e3
sorted(s, key=lambda x: (x.isdigit(),x.isdigit() and int(x) % 2 == 0,x.isupper(),x)
input: 'asdf234GDSdsf23'
output: ['a', 'd', 'd', 'f', 'f', 's', 's', 'D', 'G', 'S', '3', '3', '2', '2', '4']
- x.isdigit()的作用是把數字放在後邊(True),字母放在前面(False).
- x.isdigit() and int(x) % 2 == 0的作用是保證數字中奇數在前(False),偶數在後(True).
- x.isupper()的作用是在前面基礎上,保證字母小寫(False)在前大寫在後(True).
- 最後的x表示在前面基礎上,對所有類別數字或字母排序.