【Python】sorted排序list和dict的混合

先看看我們排序的有哪些類型的數據結構

#### 二維list排序
l1 = [['Bob', 95.00, 'A'], ['Alan', 86.0, 'C'], ['Mandy', 82.5, 'A'], ['Rob', 86, 'E']]

#### list中混合字典
l2 = [{'name':'alice', 'score':38}, {'name':'bob', 'score':18}, {'name':'darl', 'score':28}, {'name':'christ', 'score':28}]

#### 字典中混合list
d1 = {'Li': ['M', 7], 'Zhang': ['E', 2], 'Wang': ['P', 3], 'Du': ['C', 2], 'Ma': ['C', 9], 'Zhe': ['H', 7]}

#### 對字典中的多維list進行排序
d2 = {
    'Apple': [['44', 88], ['11', 33], ['22', 88]],
    'Banana': [['55', 43], ['11', 68], ['44', 22]],
    'Orange':[['22', 22], ['55', 41], ['44', 42], ['33', 22]]
}

注意: 要想學會使用sorted複雜的list和混合dict進行排序,最好先弄懂sorted如何對list和dict進行排序的,key= lambda 或itemgetter是如何對可迭代的list和dict進行元組化和比較的

1. 二維list排序

from operator import itemgetter
l1 = [['Bob', 95.00, 'A'], ['Alan', 86.0, 'C'], ['Mandy', 82.5, 'A'], ['Rob', 86, 'E']]
# 按先按成績號升序,再按成績數值升序
print(sorted(l1, key=itemgetter(2, 1), reverse=False))
# 按先按成績號升序,再按成績數值降序序
print(sorted(l1, key=lambda x:(x[2], -x[1]), reverse=False))

[[‘Mandy’, 82.5, ‘A’], [‘Bob’, 95.0, ‘A’], [‘Alan’, 86.0, ‘C’], [‘Rob’, 86, ‘E’]]
[[‘Bob’, 95.0, ‘A’], [‘Mandy’, 82.5, ‘A’], [‘Alan’, 86.0, ‘C’], [‘Rob’, 86, ‘E’]]

2. list中混合字典

from operator import itemgetter
# 先按照成績降序排序,相同成績的按照名字升序排序:
l2 = [{'name':'alice', 'score':38}, {'name':'bob', 'score':18}, {'name':'darl', 'score':28}, {'name':'christ', 'score':28}]
# 先按照成績降序排序,相同成績的按照名字升序排序:
print(sorted(l2, key=lambda x:(-x['score'], x['name'])))
# 先按照成績降序升序,相同成績的按照名字升序排序,最後取排序的逆序
print(sorted(l2, key=itemgetter('score', 'name'), reverse=True))

[{‘name’: ‘alice’, ‘score’: 38}, {‘name’: ‘christ’, ‘score’: 28}, {‘name’: ‘darl’, ‘score’: 28}, {‘name’: ‘bob’, ‘score’: 18}]
[{‘name’: ‘alice’, ‘score’: 38}, {‘name’: ‘darl’, ‘score’: 28}, {‘name’: ‘christ’, ‘score’: 28}, {‘name’: ‘bob’, ‘score’: 18}]

3. 字典中混合list

d1 = {'Li': ['M', 7], 'Zhang': ['E', 2], 'Wang': ['P', 3], 'Du': ['C', 2], 'Ma': ['C', 9], 'Zhe': ['H', 7]}
# 按value(list)裏的數組升序,再按字母降序
print(sorted(d1.items(), key=lambda x:(x[1][1], -ord(x[1][0]) )))  # 對字符比較需要ord。如果是'123'字符串數字可以使用int。
# sort返回的是list,如果需要轉爲dict,再sorted前面套一個dict()就可以了
print(dict(sorted(d1.items(), key=lambda x:(x[1][1], -ord(x[1][0]) ))))

[(‘Zhang’, [‘E’, 2]), (‘Du’, [‘C’, 2]), (‘Wang’, [‘P’, 3]), (‘Li’, [‘M’, 7]), (‘Zhe’, [‘H’, 7]), (‘Ma’, [‘C’, 9])]
{‘Zhang’: [‘E’, 2], ‘Du’: [‘C’, 2], ‘Wang’: [‘P’, 3], ‘Li’: [‘M’, 7], ‘Zhe’: [‘H’, 7], ‘Ma’: [‘C’, 9]}

4. 對字典中的多維list進行排序

d2 = {
    'Apple': [['44', 88], ['11', 33], ['22', 88]],
    'Banana': [['55', 43], ['11', 68], ['44', 22]],
    'Orange':[['22', 22], ['55', 41], ['44', 42], ['33', 22]]
}
for key, value in d2.items():
    d2[key] = sorted(value, key=lambda x:(x[1], -int(x[0]))) # 按list第二列升序,相同則按第一列降序,參考二維list排序
print(d2)

{‘Apple’: [[‘11’, 33], [‘44’, 88], [‘22’, 88]], ‘Banana’: [[‘44’, 22], [‘55’, 43], [‘11’, 68]], ‘Orange’: [[‘33’, 22], [‘22’, 22], [‘52’, 41], [‘44’, 42]]}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章