由字典元素构成的列表的排序,方法如下:

dic1={"class":"b","age":18,"num":2}
dic2={"class":"a","age":17,"num":7}
dic3={"class":"c","age":16,"num":1}
list=[]
list.append(dic1)
list.append(dic2)
list.append(dic3)
print(list)


[{'class': 'b', 'age': 18, 'num': 2}, {'class': 'a', 'age': 17, 'num': 7}, {'class': 'c', 'age': 16, 'num': 1}]
#把列表按class排序
list1=sorted(list,key=operator.itemgetter("class"))
print(list1)
#把列表按age排序
list1=sorted(list,key=operator.itemgetter("age"))
print(list1)
#把列表按num排序
list1=sorted(list,key=operator.itemgetter("num"))
print(list1)
[{'class': 'a', 'age': 17, 'num': 7}, {'class': 'b', 'age': 18, 'num': 2}, {'class': 'c', 'age': 16, 'num': 1}]
[{'class': 'c', 'age': 16, 'num': 1}, {'class': 'a', 'age': 17, 'num': 7}, {'class': 'b', 'age': 18, 'num': 2}]
[{'class': 'c', 'age': 16, 'num': 1}, {'class': 'b', 'age': 18, 'num': 2}, {'class': 'a', 'age': 17, 'num': 7}]

``

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐