如何為列表裡的字典(元組)進行排序

如何為列表裡的字典(元組)進行排序

來自專欄 python入門與實踐

有些東西,說說是不行的,要多敲代碼,看效果.下面看幾個例子:

列表中有字典

第一種方法(sorted):

goods=[{"name":"電腦","price":1999},{"name":"滑鼠","price":10},{"name":"python教程","price":688},{"name":"鍵盤","price":128},]l=sorted(goods,key=lambda x:x[price])print(l)輸出結果:[{name: 滑鼠, price: 10}, {name: 鍵盤, price: 128}, {name: python教程, price: 688}, {name: 電腦, price: 1999}]goods.sort(key=lambda x:x[price])print(goods))注意:sort()方法也是可以的.goods.sort(key=lambda x:x[price])print(goods)

第二種方法:

from operator import itemgetterli = [{"day":2},{"day":1},{"day":3}]newlist = sorted(li, key=itemgetter(day))print(newlist)輸出結果:[{day: 1}, {day: 2}, {day: 3}]

第三種方法(定義一個函數):

goods=[{"name":"電腦","price":1999},{"name":"滑鼠","price":10},{"name":"python教程","price":688},{"name":"鍵盤","price":128},]def f(x): return x[price]goods.sort(key=f)print(goods)

拓展一個按函數長度排序的:

L = [{1:5,3:4},{1:3,6:3},{1:1,2:4,5:6},{1:9}]def f(x): return len(x)L.sort(key=f)print(L)輸出:[{1: 9}, {1: 5, 3: 4}, {1: 3, 6: 3}, {1: 1, 2: 4, 5: 6}]

Python官網提供了一個很好的例子(列表中含字典):

class Student: def __init__(self, name, grade, age): self.name = name self.grade = grade self.age = age def __repr__(self): return repr((self.name, self.grade, self.age))student_objects = [ Student(john, A, 15), Student(jane, B, 12), Student(dave, B, 10),]c=sorted(student_objects, key=lambda student: student.age) # sort by ageprint(c)輸出結果:[(dave, B, 10), (jane, B, 12), (john, A, 15)]

那要是對多個排序?

a=[{status:1,com:a},{status:2 ,com:c },{status:1 ,com:b}]a.sort(key=lambda x:(x["status"],x[com]) )#先按照「status」排序,如果相同,再按照「com」排序。print(a)輸出結果:[{status: 1, com: a}, {status: 1, com: b}, {status: 2, com: c}

列表中有元組,方法和列表類似:

student_tuples = [ (john, A, 15), (jane, B, 12), (dave, B, 10), ]>>> sorted(student_tuples, key=lambda student: student[2]) # sort by age[(dave, B, 10), (jane, B, 12), (john, A, 15)]

這種很奇葩,sorted()方法(元組中有字典):

sorted({1: D, 2: B, 3: B, 4: E, 5: A})[1, 2, 3, 4, 5]

上篇文章也有提到(列表裡有元組):

L=[(b,2),(a,1),(c,3),(d,4)]sorted(L, key=lambda x:x[1]) Out[40]: [(a, 1), (b, 2), (c, 3), (d, 4)]students = [(john, A, 15), (jane, B, 12), (dave, B, 10)]sorted(students, key=lambda s: s[2]) Out[42]: [(dave, B, 10), (jane, B, 12), (john, A, 15)]sorted(students, key=lambda s: s[2], reverse=True) Out[43]: [(john, A, 15), (jane, B, 12), (dave, B, 10)]

是不是很厲害,掌握一種就可以,其實Python還有很多很多的方法,到官網上去發現寶貝吧.


推薦閱讀:

python字元串
第十三章 Python: xml轉json
為什麼 Nginx 已經這麼成熟,Python 還有各種如 web.py 等 web 框架?
Python在Finance上的應用:獲取股票價格

TAG:編程 | Python | Python入門 |