歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python字典數組排序實現

Python字典數組排序實現

日期:2017/3/1 10:24:10   编辑:Linux編程

python對容器內數據的排序有兩種,一種是容器自己的sort函數,一種是內建的sorted函數。

sort函數和sorted函數唯一的不同是,sort是在容器內排序,sorted生成一個新的排好序的容器

eg數組排序:

L=[5,2,3,1,4].

sort: L.sort()

sorted(...)
sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list

eg字典排序:

按照key倒序排列輸出

records = {'aapl':4.0, 'abandon': 4.0, 'absenc': 3.0,}

recordsort= sorted(records.items(),key=lambda records:records[0],reverse=True)
f = file ('/data/ebi/meta/channelxlsexport/Datasrc'+date+'.csv', 'w')
for line in recordsort:
f.write(line[1]+'\n')
f.close()

OrderedDict是collections中的一個包,能夠記錄字典元素插入的順序,常常和排序函數一起使用來生成一個排序的字典。

比如,比如一個無序的字典

d = {‘banana’:3,’apple’:4,’pear’:1,’orange’:2}

通過排序來生成一個有序的字典,有以下幾種方式

collections.OrderedDict(sorted(d.items(),key = lambda t:t[0]))

或者

collections.OrderedDict(sorted(d.items(),key = lambda t:t[1]))

或者

collections.OrderedDict(sorted(d.items(),key = lambda t:len(t[0])))

Copyright © Linux教程網 All Rights Reserved