由字典元素构成的列表的排序方法
由字典元素构成的列表的排序,方法如下: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)```pyth
·
由字典元素构成的列表的排序,方法如下:
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}]
``
更多推荐
已为社区贡献1条内容
所有评论(0)